我正在运行SQL Server查询的问题,我无法弄清楚如何让它正常工作。我尝试根据分类的类别获取MAX日期。我知道这听起来很混乱,所以让我解释一下我想要的结果。
我们说我有这张桌子:
Table1
Category Value UpdatedDateTime
Cat1 5 2017-11-12 10:46
Cat1 2 2017-11-13 11:46
Cat1 4 2017-11-13 10:46
Cat2 5 2017-11-12 10:46
Cat2 7 2017-11-12 11:46
Cat2 3 2017-11-13 09:46
Cat3 1 2017-11-12 10:46
Cat3 2 2017-11-12 11:46
Cat3 7 2017-11-13 11:46
Cat3 8 2017-11-13 10:46
Cat3 3 2017-11-10 10:46
Cat4 4 2017-11-13 10:46
Cat4 4 2017-11-12 10:46
我希望结果中的UpdatedDateTime通过类别分组选择最新日期,如下所示:
Category Value UpdatedDateTime
Cat1 5 2017-11-13 11:46
Cat1 2 2017-11-13 11:46
Cat1 4 2017-11-13 11:46
Cat2 5 2017-11-13 09:46
Cat2 7 2017-11-13 09:46
Cat2 3 2017-11-13 09:46
Cat3 1 2017-11-13 11:46
Cat3 2 2017-11-13 11:46
Cat3 7 2017-11-13 11:46
Cat3 8 2017-11-13 11:46
Cat3 3 2017-11-13 11:46
Cat4 4 2017-11-13 10:46
Cat4 4 2017-11-13 10:46
我尝试了这个查询,但当然它不起作用,因为我正在为整个表寻找Max(UpdatedDate),而不是按类别。然后我卡住了。
With cte AS
(
Select Category, Value, UpdatedDateTime FROM Table1
)
Select Category, Sum(Value)
, (Select Top 1 Max(UpdatedDateTime) FORM cte) AS UpdatedDateTime
FROM cte
Group By Category
请提前帮助,谢谢。
答案 0 :(得分:1)
您可以轻松地使用分区窗口功能。
declare @Something table
(
Category varchar(10)
, MyValue int
, UpdatedDateTime datetime
)
insert @Something values
('Cat1', 5, '2017-11-12 10:46')
, ('Cat1', 2, '2017-11-13 11:46')
, ('Cat1', 4, '2017-11-13 10:46')
, ('Cat2', 5, '2017-11-12 10:46')
, ('Cat2', 7, '2017-11-12 11:46')
, ('Cat2', 3, '2017-11-13 09:46')
, ('Cat3', 1, '2017-11-12 10:46')
, ('Cat3', 2, '2017-11-12 11:46')
, ('Cat3', 7, '2017-11-13 11:46')
, ('Cat3', 8, '2017-11-13 10:46')
, ('Cat3', 3, '2017-11-10 10:46')
, ('Cat4', 4, '2017-11-13 10:46')
, ('Cat4', 4, '2017-11-12 10:46')
select Category
, MyValue
, UpdatedDateTime = MAX(UpdatedDateTime) over(partition by Category)
from @Something
答案 1 :(得分:1)
SELECT t1.Category, t1.Value, t2.maxDate AS UpdatedDateTime
FROM Table1 AS t1
INNER JOIN (Select Category, Max(UpdatedDateTime) AS maxDate FROM Table1 Group By Category)
t2 ON t2.Category = t1.Category
答案 2 :(得分:0)
试试这个,你总是得到每个类别中的最新行
SELECT * FROM
(SELECT ROW_NUMBER()
OVER (PARTITION BY Category ORDER BY UpdatedDateTime DESC) AS RowNum,
* FROM Table1) AS Table2 WHERE RowNum = 1