Sql server 如何选择日期、ID、每个ID的最大日期月份的数量
我有Sql server 如何选择日期、ID、每个ID的最大日期月份的数量,sql-server,Sql Server,我有 Date ID Qty 2019/4/1 A 11 2019/5/1 A 22 2019/6/1 A 33 'need (Maximum Month of A) 2019/6/2 A 44 'need (Maximum Month of A) 2019/7/1 B 55 'need (Maximum Month of B) 2019/7/2 B 66 'need (Maximum
Date ID Qty
2019/4/1 A 11
2019/5/1 A 22
2019/6/1 A 33 'need (Maximum Month of A)
2019/6/2 A 44 'need (Maximum Month of A)
2019/7/1 B 55 'need (Maximum Month of B)
2019/7/2 B 66 'need (Maximum Month of B)
2019/6/1 B 77
2019/5/1 B 88
我需要在每个ID的最大日期月份的所有行,如下所示
Date ID Qty
2019/6/1 A 33
2019/6/2 A 44
2019/7/1 B 55
2019/7/2 B 66
这就是解决方案:
WITH RankedTable AS(
SELECT *, RANK() OVER (PARTITION BY ID ORDER BY DATEPART(MONTH, "Date") DESC) AS RankMonth
FROM @Table
)
SELECT "Date", ID, Qty
FROM RankedTable
WHERE RankMonth = 1
如果您希望max在一年和一个月内:
WITH RankedTable AS(
SELECT *, RANK() OVER (PARTITION BY ID ORDER BY DATEPART(YEAR, "Date") DESC, DATEPART(MONTH, "Date") DESC) AS RankYearMonth
FROM @Table
)
SELECT "Date", ID, Qty
FROM RankedTable
WHERE RankYearMonth = 1
我真的不明白你是如何以任何方式得出这个结果的。你能再解释一下你的逻辑吗?结果与(不清楚的)描述不匹配,发布未排序的数据也没有帮助。您正在寻找每月数量最大的ID吗?在这种情况下,为什么结果中有两行6月?为什么结果中没有
2019/6/1 B 77
。请再次查看。@PanagiotisKanavos该行不是ID Bi的最大月份,将在周一进行测试,谢谢。它有效。非常感谢。