大家好,请帮我说明如何实现这个结果,我有以下表数据
AutoID Quantity
1 2
2 2
3 2
4 7
5 7
6 2
7 2
使用min
和max
:
Select Min(AutoID) as AutoIDMin, Min(AutoID) as AutoIDMax, Quantity
from table1 GROUP By Quantity
我的结果是:
AutoIDMin - AutoIDMax - Quantity
1 7 2
4 5 7
我想要实现的目标如下:
AutoIDMin AutoIDMax Quantity
1 3 2
4 5 7
6 7 2
希望你能帮助我。
答案 0 :(得分:3)
使用ROW_NUMBER
s的差异:
WITH Cte AS(
SELECT *,
grp = ROW_NUMBER() OVER(ORDER BY AutoID)
- ROW_NUMBER() OVER(PARTITION BY Quantity ORDER BY AutoID)
FROM tbl
)
SELECT
AutoIDMin = MIN(AutoID),
AutoIDMax = MAX(AutoID),
Quantity
FROM Cte
GROUP BY grp, Quantity
ORDER BY AutoIDMin
以下是Jeff Moden关于群岛分组的文章: Group Island of Contiguous Dates