如何在SQL Server中加入聚合函数结果?

时间:2018-06-13 19:12:09

标签: sql sql-server tsql select

我正在使用列查询市场分钟数据表:

date, time, symbol, open, high, low, close

我想获得每一天的最后一栏。这就是我想出的:

select 
    a.[Date], a.Symbol, Max(a.[Time]) as max_time, b.[Close] 
from 
    MinuteData2016 as a
join 
    MinuteData2016 as b on a.[Date] = b.[Date] 
                        and a.Symbol = b.Symbol 
                        and b.Time = max_time 
where
    (a.Symbol = 'AAPL' or a.Symbol = 'ADBE')
    and (a.[Date]=20171102 or a.[Date]= 20171103 )
    and a.[Time] > 1600
group by 
    a.Symbol, a.[Date]

我收到此错误:

  

列名称无效' max_time'。

1 个答案:

答案 0 :(得分:4)

我认为使用窗口函数实现这一目标要容易得多:

SELECT [date], [symbol], [time], [close]
FROM   (SELECT [date], [symbol], [time], [close],
               ROW_NUMBER() OVER (PARTITION BY [date], [symbol]
                                  ORDER BY [time] DESC) AS rn
        FROM   MinuteData2016
        WHERE  [symbol] IN ('AAPL', 'ADBE') AND
               [Date] IN (20171102, 20171103) AND
               [time] > 1600) t
WHERE  t.rn = 1