2

我有以下选择结果

代码 价格 年份
1 200 2013
1 100 2012
2 250 2011
2 275 2012
2 300 2010

但是我想用一个额外的列来跟踪这样的事情,该列根据最大年份保存价格,

代码 价格 年份 ExPrice
1 200 2013 200
1 100 2012 200
2 250 2011 275
2 275 2012 275
2 300 2010 275

很抱歉英语不好和问这个问题的方式不对。

4

2 回答 2

1

尝试这样的事情:

SELECT T1.Code, T1.Price, T1.Year, T2.Price
FROM Table T1
INNER JOIN Table T2 ON T1.Code = T2.Code AND
    T2.Year = (SELECT MAX(Year) FROM Table WHERE Table.Code = T2.Code)
于 2013-08-23T12:50:42.290 回答
1

你可以用cross applyand做到这一点select top 1 ... order by

select Code, Price, Year, ExPrice
from TableName T
    cross apply (
        select top 1 Price
        from TableName
        where Code = T.Code
        order by Year desc
    ) p(ExPrice)

row_numberjoin(无论你喜欢什么):

;with cte as (
    select Code, Price as ExPrice, rn = row_number() over (partition by Code order by Year desc)
    from TableName
)
select T.Code, Price, Year, ExPrice
from TableName T
    join cte on cte.Code = T.Code and cte.rn = 1

SQLFiddle 示例

于 2013-08-23T13:00:33.853 回答