获取第二个最新日期的价格的SQL查询

时间:2012-12-14 09:10:25

标签: sql sql-server syntax

我有这个问题:

select @cost = @cost +                  
    (select top 1 price from
    (select top 2 price, date  from myTable order by date DESC)
     order by date ASC
)

我收到错误:关键字'order'附近的语法不正确。 如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

我想这个子查询

(select top 2 price, date  from myTable order by date DESC)

需要一个别名,比如

(select top 2 price, date  from myTable order by date DESC) sq

但我会这样写:

SELECT @cost = @cost + (
SELECT price FROM (
SELECT price, date, ROW_NUMBER() OVER (ORDER BY date DESC) AS rownum
) sq WHERE rownum = 2
)