Partitioning

查找具有等值字元的連續記錄

  • May 14, 2018

我需要您的支持來解決這個問題。

我有一個表包含類似於以下數據:

|AccountNo|remarks    |
|Q32571   |Actual Read|
|Q32571   |Locked     |
|Q32571   |Actual Read|
|Q32571   |Actual Read|
|Q32571   |Actual Read|
|Q32571   |Locked     |
|Q32571   |Actual Read|

預期的結果應該只給我相同的備註的連續記錄

|AccountNo|TotCont|
|Q32571   |    3  |

誰能幫忙

謝謝

正如評論中提到的,您需要有一種方法來確定行的順序,因此我在ID範例中添加了一個列。我還添加了另一個AccountNumber並將數據混合了一下,以驗證我的解決方案是否適用於其他帳戶。您沒有指定您的 RDBMS。我的解決方案使用 SQL Server。

--Set up demo data
DECLARE @T TABLE
   ([ID] int,[AccountNumber] varchar(10), [Remarks] varchar(100))
;

insert into @t(ID,AccountNumber,Remarks) values
(1,'Q32571','Actual Read'),
(2,'Q32571','Locked'),
(3,'Q11111','Locked'),
(4,'Q11111','Locked'),
(5,'Q32571','Actual Read'),
(6,'Q32571','Actual Read'),
(7,'Q32571','Actual Read'),
(8,'Q32571','Locked'),
(9,'Q32571','Actual Read'),
(10,'Q11111','Actual Read'),
(11,'Q11111','Locked')
;

--The actual query 
;with _groupings as
(
select AccountNumber, Remarks, count(*) as CountConsecutive
from (select t.*,
            (row_number() over (order by AccountNumber, ID) -
             row_number() over (partition by Remarks order by AccountNumber,ID)
            ) as grp
     from @t t
    ) t
group by AccountNumber, grp, Remarks
)
select AccountNumber, Max(CountConsecutive) as CountConsecutive
from _groupings 
group by AccountNumber

| AccountNumber | CountConsecutive |
|---------------|------------------|
| Q11111        | 2                |
| Q32571        | 3                |

引用自:https://dba.stackexchange.com/questions/206590