gpt4 book ai didi

sql - 获取所有不同值的连续行?

转载 作者:行者123 更新时间:2023-12-02 19:54:11 28 4
gpt4 key购买 nike

我正在尝试这样做,因为它涉及连续行的比较。我正在尝试将相差一定数字的值分组。例如,假设我有这张表:

CREATE TABLE #TEMP (A int, B int)

-- Sample table
INSERT INTO #TEMP VALUES
(3,1),
(3,2),
(3,3),
(3,4),
(5,1),
(6,1),
(7,2),
(8,3),
(8,4),
(8,5),
(8,6)

SELECT * FROM #TEMP

DROP TABLE #TEMP

假设我必须将所有相差 1 且 A 具有相同值的值分组。然后我尝试获得如下输出:

A B GroupNo
3 1 1
3 2 1
3 3 1
3 4 1
5 1 2
6 1 3
7 2 4
8 3 5
8 4 5
8 5 5
8 6 5

(3,1) (3,2) (3,3) (3,4)(8,3) (8,4) (8,5) ( 8,6) 已被放入同一组,因为它们的值相差 1。我将首先展示我的尝试:

CREATE TABLE #TEMP (A int, B int)

-- Sample table
INSERT INTO #TEMP VALUES
(3,1), (3,2), (3,3), (3,4), (5,1), (6,1), (7,2),
(8,3), (8,4), (8,5), (8,6)

-- Assign row numbers and perform a left join
-- so that we can compare consecutive rows
SELECT ROW_NUMBER() OVER (ORDER BY A ASC) ID, *
INTO #TEMP2
FROM #TEMP

;WITH CTE AS
(
SELECT X.A XA, X.B XB, Y.A YA, Y.B YB
FROM #TEMP2 X
LEFT JOIN #TEMP2 Y
ON X.ID = Y.ID - 1
WHERE X.A = Y.A AND
X.B = Y.B - 1
)
SELECT XA, XB
INTO #GROUPS
FROM CTE
UNION
SELECT YA, YB
FROM CTE
ORDER BY XA ASC

-- Finally assign group numbers
SELECT X.XA, X.XB, Y.GID
FROM #GROUPS X
INNER JOIN
(SELECT XA, ROW_NUMBER() OVER (ORDER BY XA ASC) GID
FROM #GROUPS Y
GROUP BY XA
) Y
ON X.XA = Y.XA

DROP TABLE #TEMP
DROP TABLE #TEMP2
DROP TABLE #GROUPS

我将在一个大表(大约 3000 万行)上执行此操作,因此我希望有一种更好的方法可以对任意值执行此操作(例如,不只是相差 1,还可以是 2 或 3)我稍后会将其纳入程序中)。关于我的方法是否没有错误以及是否可以改进有什么建议吗?

最佳答案

对于它们不同的情况,您可以使用

;WITH T AS
(
SELECT *,
B - DENSE_RANK() OVER (PARTITION BY A ORDER BY B) AS Grp
FROM #TEMP
)
SELECT A,
B,
DENSE_RANK() OVER (ORDER BY A,Grp) AS GroupNo
FROM T
ORDER BY A, Grp

更一般地说

DECLARE @Interval INT = 2

;WITH T AS
(
SELECT *,
B/@Interval - DENSE_RANK() OVER (PARTITION BY A, B%@Interval ORDER BY B) AS Grp
FROM #TEMP
)
SELECT A,
B,
DENSE_RANK() OVER (ORDER BY A, B%@Interval,Grp) AS GroupNo
FROM T
ORDER BY A, GroupNo

关于sql - 获取所有不同值的连续行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7854854/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com