TSQL
DECLARE @Temp TABLE
(
ID int identity(1,1) ,
Col1 char(1)
)
INSERT INTO @Temp VALUES
('A') , ('A') , ('A') , ('B') , ('C') , ('C') , ('A') , ('A') , ('A')
;
WITH T1 AS
(
SELECT
* ,
-- 第三參數:null 的預設值
LAG(Col1 , 1 , Col1) OVER (ORDER BY ID)AS PreValue
FROM @Temp
)
, T2 AS
(
SELECT
* ,
-- 判斷連續字串是否有變
CAST(IIF(Col1 = PreValue , 0 , 1) AS int) AS GroupChange
FROM T1
)
, T3 AS
(
SELECT
* ,
-- 使用彙總視窗函數跑 Running Total
SUM(GroupChange) OVER (ORDER BY ID ROWS UNBOUNDED PRECEDING) AS GroupNO
FROM T2
)
SELECT *
FROM T3
ORDER BY ID
LAG default 參數
The value to return when offset is beyond the scope of the partition. If a default value is not specified, NULL is returned. default can be a column, subquery, or other expression, but it cannot be an analytic function. default must be type-compatible with scalar_expression.
沒有留言:
張貼留言