我有一个带有ID列的表和另一个带有数字的列。一个ID可以有多个数字。例如
ID | Number
1 | 25
1 | 26
1 | 30
1 | 24
2 | 4
2 | 8
2 | 5
现在根据这些数据,在一个新表中,我希望有这个
ID | Low | High
1 | 24 | 26
1 | 30 | 30
2 | 4 | 5
2 | 8 | 8
正如你所看到的,我想合并任何数字连续的数据,如24,25,26。所以现在低点是24,高点是26,然后30仍然是一个单独的范围。我正在处理大量的数据,所以我宁愿不使用游标来提高性能(这是我以前做过的事情,而且速度相当缓慢)......实现这个目标的最佳方法是什么? ?我不是SQL专家,所以我不确定是否有可用的功能可以使这更容易,或者最快的方法是什么。
感谢您的帮助。
答案 0 :(得分:36)
关键观察是一系列数字减去另一个序列是一个常数。我们可以使用row_number
生成另一个序列。这标识了所有组:
select id, MIN(number) as low, MAX(number) as high
from (select t.*,
(number - ROW_NUMBER() over (partition by id order by number) ) as groupnum
from t
) t
group by id, groupnum
其余的只是聚合。
答案 1 :(得分:3)
CTE和递归的解决方案:
WITH CTE AS (
SELECT T.ID, T.NUMBER, T.NUMBER AS GRP
FROM T
LEFT OUTER JOIN T T2 ON T.ID = T2.ID AND T.NUMBER -1 = T2.NUMBER
WHERE T2.ID IS NULL
UNION ALL
SELECT T.ID, T.NUMBER, GRP
FROM CTE
INNER JOIN T
ON T.ID = CTE.ID AND T.NUMBER = CTE.NUMBER + 1
)
SELECT ID, MAX( NUMBER ), MIN(NUMBER)
FROM CTE
GROUP BY ID, GRP
答案 2 :(得分:0)
我建议使用WHILE
循环结构和表变量而不是光标。
例如,
DECLARE @TableVariable TABLE
(
MyID int IDENTITY (1, 1) PRIMARY KEY NOT NULL,
[ID] int,
[Number] int
)
DECLARE @Count int, @Max int
INSERT INTO @TableVariable (ID, Number)
SELECT ID, Number
FROM YourSourceTable
SELECT @Count = 1, @Max = MAX(MyID)
FROM @TableVariable
WHILE @Count <= @Max
BEGIN
...do your processing here...
SET @Count = @Count + 1
END
答案 3 :(得分:0)
CREATE TABLE Table1
([ID] int, [Number] int)
;
INSERT INTO Table1
([ID], [Number])
VALUES
(1, 25),
(1, 26),
(1, 30),
(1, 24),
(2, 4),
(2, 8),
(2, 5)
;
select ID,
MIN(Number)
,(SELECT MIN(Number)
FROM (SELECT TOP 2 Number from Table1 WHERE ID =
T1.Id ORDER BY Number DESC) as DT)
from Table1 as T1
GROUP BY ID
UNION
SELECT ID, MAX(Number), MAX(Number)
FROM Table1 as T1
GROUP BY ID;