這看起來像經典gaps-and-islands
問題。 在下面的查詢中檢查每個CTE的中間結果,以瞭解發生了什麼。
的樣本數據
我添加人員3
有陽性結果的兩個序列,這樣我們就可以找到最長的序列。
DECLARE @T TABLE (id int, person int, result int);
INSERT INTO @T (id, person, result) VALUES
(1 , 1, 0),
(2 , 1, 1),
(3 , 1, 1),
(4 , 2, 1),
(5 , 2, 0),
(6 , 1, 1),
(7 , 1, 0),
(8 , 2, 0),
(9 , 2, 0),
(10, 2, 0),
(11, 3, 0),
(12, 3, 1),
(13, 3, 1),
(14, 3, 1),
(15, 3, 1),
(16, 3, 0),
(17, 3, 1),
(18, 3, 1),
(19, 3, 0),
(20, 3, 0);
查詢
WITH
CTE_RowNumbers
AS
(
SELECT
id, person, result
,ROW_NUMBER() OVER (PARTITION BY person ORDER BY ID) AS rn1
,ROW_NUMBER() OVER (PARTITION BY person, result ORDER BY ID) AS rn2
FROM @T
)
,CTE_Groups
AS
(
SELECT
id, person, result
,rn1-rn2 AS GroupNumber
FROM CTE_RowNumbers
)
,CTE_GroupSizes
AS
(
SELECT
person
,COUNT(*) AS GroupSize
FROM CTE_Groups
WHERE
result = 1
GROUP BY
person
,GroupNumber
)
SELECT
person
,MAX(GroupSize) AS max_count
FROM CTE_GroupSizes
GROUP BY person
ORDER BY person;
結果
+--------+-----------+
| person | max_count |
+--------+-----------+
| 1 | 3 |
| 2 | 1 |
| 3 | 4 |
+--------+-----------+
提示:'gap-and-islands'。什麼是SQL Server的版本?我想我可以寫最後的查詢,但有一點不清楚。爲什麼人'1'的'max_count'是'2'?根據你的樣品,它應該是'3',不是?行ID:'2,3,6'。行'4,5'是針對不同的人,我認爲他們應該被忽視,不是嗎?或者,您是否對嚴格的「連續」序列感興趣,其中ID **必須**在沒有任何間隙的序列中?如果您在示例中添加更多的行來解釋不同的變體,這將有助於理解您需要的內容。 –
@VladimirBaranov你是對的。我在這個問題上犯了一個錯誤。現在將糾正。 – ydoow