我想按日期对数据进行分组,然后找到" Value"对于MAX(" SeqNumber")。如何在聚合查询中执行此操作。
我尝试了以下内容,但它给出了错误。
专栏' MyTable.SeqNumber'在选择列表中无效,因为它是 不包含在聚合函数或GROUP BY子句中。 Msg 8120,Level 16,State 1,Line 22 Column' MyTable.Value'是无效的 在选择列表中,因为它不包含在聚合中 函数或GROUP BY子句。
Columns:
Date: date
Time: time
Value: float
Code: varchar <<Added in EDIT
SeqNumber: int
编辑查询:
SELECT MAX(case [Code] when 'GOLD' then [Value] end) AS BestGold,
MAX(case [Code] when 'SILVER' then [Value] end) as BestSilver
(CASE WHEN [SeqNumber]=MAX([SeqNumber]) THEN [Value] END) AS HIGHEST << Problem
FROM [MyTable]
GROUP BY [Date]
答案 0 :(得分:0)
WITH CTE AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY [Date] ORDER BY Sequence DESC) AS RN
FROM YourTable)
SELECT [Value] AS Highest
FROM CTE
WHERE RN = 1;
答案 1 :(得分:0)
您可以使用group by和sub query -
来实现此目的select t1.*
from [MyTable] t1 join
( SELECT
MAX([SeqNumber]) as MX_SeqNumber -- you can add your additional columns here
FROM [MyTable]
GROUP BY [Date] ) as t2
on t1.[SeqNumber] = t2.MX_SeqNumber