問:如何根據1列的更改值對記錄進行排名?根據1列的更改值排列記錄
我有如下數據(https://pastebin.com/vdTb1JRT):
EmployeeID Date Onleave
ABH12345 2016-01-01 0
ABH12345 2016-01-02 0
ABH12345 2016-01-03 0
ABH12345 2016-01-04 0
ABH12345 2016-01-05 0
ABH12345 2016-01-06 0
ABH12345 2016-01-07 0
ABH12345 2016-01-08 0
ABH12345 2016-01-09 0
ABH12345 2016-01-10 1
ABH12345 2016-01-11 1
ABH12345 2016-01-12 1
ABH12345 2016-01-13 1
ABH12345 2016-01-14 0
ABH12345 2016-01-15 0
ABH12345 2016-01-16 0
ABH12345 2016-01-17 0
我想產生以下結果:
EmployeeID DateValidFrom DateValidTo OnLeave
ABH12345 2016-01-01 2016-01-09 0
ABH12345 2016-01-10 2016-01-13 1
ABH12345 2016-01-14 2016-01-17 0
所以我想,如果我能以某種方式創建一個排名列(如下所示),該值根據Onleave列中的值增加 - 由EmployeeID列分區。
EmployeeID Date Onleave RankedCol
ABH12345 2016-01-01 0 1
ABH12345 2016-01-02 0 1
ABH12345 2016-01-03 0 1
ABH12345 2016-01-04 0 1
ABH12345 2016-01-05 0 1
ABH12345 2016-01-06 0 1
ABH12345 2016-01-07 0 1
ABH12345 2016-01-08 0 1
ABH12345 2016-01-09 0 1
ABH12345 2016-01-10 1 2
ABH12345 2016-01-11 1 2
ABH12345 2016-01-12 1 2
ABH12345 2016-01-13 1 2
ABH12345 2016-01-14 0 3
ABH12345 2016-01-15 0 3
ABH12345 2016-01-16 0 3
ABH12345 2016-01-17 0 3
然後,我將能夠做到以下幾點:
SELECT
[EmployeeID] = [EmployeeID]
,[DateValidFrom] = MIN([Date])
,[DateValidTo] = MAX([Date])
,[OnLeave] = [OnLeave]
FROM table/view/cte/sub-query
GROUP BY
[EmployeeID]
,[OnLeave]
,[RankedCol]
其他解決方案都非常歡迎..
下面是測試數據:
WITH CTE AS (SELECT EmployeeID = 'ABH12345', [Date] = CAST(N'2016-01-01' AS Date), [Onleave] = 0
UNION SELECT 'ABH12345', CAST(N'2016-01-02' AS Date), 0
UNION SELECT 'ABH12345', CAST(N'2016-01-03' AS Date), 0
UNION SELECT 'ABH12345', CAST(N'2016-01-04' AS Date), 0
UNION SELECT 'ABH12345', CAST(N'2016-01-05' AS Date), 0
UNION SELECT 'ABH12345', CAST(N'2016-01-06' AS Date), 0
UNION SELECT 'ABH12345', CAST(N'2016-01-07' AS Date), 0
UNION SELECT 'ABH12345', CAST(N'2016-01-08' AS Date), 0
UNION SELECT 'ABH12345', CAST(N'2016-01-09' AS Date), 0
UNION SELECT 'ABH12345', CAST(N'2016-01-10' AS Date), 1
UNION SELECT 'ABH12345', CAST(N'2016-01-11' AS Date), 1
UNION SELECT 'ABH12345', CAST(N'2016-01-12' AS Date), 1
UNION SELECT 'ABH12345', CAST(N'2016-01-13' AS Date), 1
UNION SELECT 'ABH12345', CAST(N'2016-01-14' AS Date), 0
UNION SELECT 'ABH12345', CAST(N'2016-01-15' AS Date), 0
UNION SELECT 'ABH12345', CAST(N'2016-01-16' AS Date), 0
UNION SELECT 'ABH12345', CAST(N'2016-01-17' AS Date), 0
)
SELECT * FROM CTE
加1的樣本數據 – TheGameiswar
提示:這是有幫助的標記同時與相應的軟件數據庫的問題(MySQL和甲骨文,DB2,...)和版本,例如'的SQL服務器2014'。語法和功能的差異往往會影響答案。在這種情況下,滯後是一個相對較新的特徵。 – HABO
增加了sql-server-2014,謝謝@HABO –