选择每组的第一条和最后一条记录
我需要返回每组集合的第一个和最后一个记录。
数据:
Code Close Time
USD 146116 2022-04-03 04:00:00.00 +00:00
EUR 241789 2022-03-27 17:00:00.00 +00:00
EUR 241807 2022-03-27 08:00:00.00 +00:00
USD 141800 2022-03-27 08:00:00.00 +00:00
USD 140809 2022-03-27 07:00:00.00 +00:00
T-SQL:
SELECT
[Code]
,DATEADD(dd, 0, DATEDIFF(dd, 0, [Time]))
,FIRST_VALUE([Close]) OVER (ORDER BY [Time] ASC) AS [Open] -- Column 'Time' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
,MAX([Close]) AS [High]
,MIN([Close]) AS [Low]
,LAST_VALUE([Close]) OVER (ORDER BY [Time] ASC) AS [Close] -- Column 'Time' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
FROM [CurrencyIntradayHistories]
GROUP BY [Code],
DATEADD(dd, 0, DATEDIFF(dd, 0, [Time]))
ORDER BY [Time] ASC
期望的结果:
Code Open High Low Close Time
EUR 241807 241807 241789 241789 2022-03-27
USD 140809 141800 140809 141800 2022-03-27
USD 146116 146116 146116 146116 2022-04-03
I need to return the first and last record of each group of sets.
DATA:
Code Close Time
USD 146116 2022-04-03 04:00:00.00 +00:00
EUR 241789 2022-03-27 17:00:00.00 +00:00
EUR 241807 2022-03-27 08:00:00.00 +00:00
USD 141800 2022-03-27 08:00:00.00 +00:00
USD 140809 2022-03-27 07:00:00.00 +00:00
T-SQL:
SELECT
[Code]
,DATEADD(dd, 0, DATEDIFF(dd, 0, [Time]))
,FIRST_VALUE([Close]) OVER (ORDER BY [Time] ASC) AS [Open] -- Column 'Time' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
,MAX([Close]) AS [High]
,MIN([Close]) AS [Low]
,LAST_VALUE([Close]) OVER (ORDER BY [Time] ASC) AS [Close] -- Column 'Time' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
FROM [CurrencyIntradayHistories]
GROUP BY [Code],
DATEADD(dd, 0, DATEDIFF(dd, 0, [Time]))
ORDER BY [Time] ASC
Desired result:
Code Open High Low Close Time
EUR 241807 241807 241789 241789 2022-03-27
USD 140809 141800 140809 141800 2022-03-27
USD 146116 146116 146116 146116 2022-04-03
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能直接在此处使用
first_value
,因为它是窗口函数,而不是聚合函数。您需要将其嵌入子查询/派生表中,并在其上使用聚合。
此外,它需要按子句进行
分区,以及
在未绑定的前面和无限制之间的行
略有效率的版本使用
row_number
和LEAD
找到起始和结束行。You cannot use
FIRST_VALUE
directly here because it is a window function, not an aggregate function.You need to embed it in a subquery/derived table and use aggregation over it.
Also, it needs a
PARTITION BY
clause, as well asROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
A slightly more efficient version uses
ROW_NUMBER
andLEAD
to find the starting and ending rows.db<>fiddle
在整个数据集上使用窗口函数 MIN()、MAX() 和 FIRST_VALUE(),而不是在按代码和日期分组时得到的结果上使用:
请参阅 演示。
Use window functions MIN(), MAX() and FIRST_VALUE() on the whole dataset and not on the results that you get if you group by Code and date:
See the demo.