基本解使用DENSE_RANK Window Function:
CREATE TABLE #Data(ID INT IDENTITY, MATERIAL VARCHAR(10), NEW_OPR_SEQ INT, WORKCENTER VARCHAR(20))
INSERT INTO #Data
VALUES
('070147', 1, 'MONSO003'), ('070147', 2, 'MONSO003'), ('070147', 3, 'MONSO003'), ('070147', 4, 'MONSO003'),
('070147', 5, 'MONSO003'), ('070147', 6, 'MONGR025'), ('070147', 7, 'VERSA008'), ('070147', 8, 'LAGER'),
('912001', 1, 'MONGR025'), ('912001', 2, 'VERSA008'), ('912001', 3, 'VERSA008')
SELECT *,
DENSE_RANK() OVER(PARTITION BY MATERIAL, WORKCENTER, NEW_OPR_SEQ % 2 ORDER BY NEW_OPR_SEQ) AS GroupNumber
FROM #Data
輸出:
ID MATERIAL NEW_OPR_SEQ WORKCENTER GroupNumber
----------- ---------- ----------- -------------------- --------------------
1 070147 1 MONSO003 1
2 070147 2 MONSO003 1
3 070147 3 MONSO003 2
4 070147 4 MONSO003 2
5 070147 5 MONSO003 3
6 070147 6 MONGR025 1
7 070147 7 VERSA008 1
8 070147 8 LAGER 1
9 912001 1 MONGR025 1
10 912001 2 VERSA008 1
11 912001 3 VERSA008 1
說明:
DENSE_RANK()
- 窗口函數像內聯GROUP BY
聲明一樣工作;上面的代碼按照'MATERIAL'和'WORKCENTER'和'NEW_OPR_SEQ%2'將行分成(見PARTITION BY
部分)行。 'NEW_OPR_SEQ'列提供的訂單(參見ORDER BY
)編號爲1到n的每個組的記錄
NEW_OPR_SEQ % 2
- 是允許整個事情工作的訣竅。該代碼返回整數除以2的餘數,即偶數爲0,奇數爲1。實質上,這段代碼將你的行分成偶數和奇數。
如果你想返回一個0,其中一個記錄沒有匹配的記錄,那麼你可以使用COUNT()
功能如下:
SELECT *,
CASE WHEN COUNT(*) OVER(PARTITION BY MATERIAL, WORKCENTER, GroupNumber) = 1 THEN 0
ELSE GroupNumber
END AS GroupNumberOrZero
FROM (
SELECT *,
DENSE_RANK() OVER(PARTITION BY MATERIAL, WORKCENTER, NEW_OPR_SEQ % 2 ORDER BY NEW_OPR_SEQ) AS GroupNumber
FROM #Data) AS Ranked
ORDER BY ID
輸出:
ID MATERIAL NEW_OPR_SEQ WORKCENTER GroupNumber GroupNumberOrZero
----------- ---------- ----------- -------------------- -------------------- --------------------
1 070147 1 MONSO003 1 1
2 070147 2 MONSO003 1 1
3 070147 3 MONSO003 2 2
4 070147 4 MONSO003 2 2
5 070147 5 MONSO003 3 0
6 070147 6 MONGR025 1 0
7 070147 7 VERSA008 1 0
8 070147 8 LAGER 1 0
9 912001 1 MONGR025 1 0
10 912001 2 VERSA008 1 1
11 912001 3 VERSA008 1 1
對不起納文,但我已經多次閱讀你的問題,我仍然不明白你在問什麼。如果你包含了輸入數據,這可能會有所幫助。 –
他希望爲兩組的序列號生成序列號,而不是序列號。例如,1和2,應該有序列號爲1,3和4應該有序列號爲2,5和6應該有序列號爲3,依此類推。 –
@navin,你能提供輸入數據嗎? –