我有一個記錄看起來如下做單記錄多個記錄在SQL Server
從兩排,我想分裂ShiftPattern值,並創建多個記錄,並StartWeek將依次產生。
最終查詢:
- 拆分ShiftPattern柱和創建多個記錄
- 增加StartWeek像20,21旋轉。
輸出結果
我有一個記錄看起來如下做單記錄多個記錄在SQL Server
從兩排,我想分裂ShiftPattern值,並創建多個記錄,並StartWeek將依次產生。
最終查詢:
輸出結果
這是你所需要的。在小提琴測試。
select q.locationid,q.employeeid,
case
when (lag(employeeid,1,null) over (partition by employeeid order by weekshiftpatternid)) is null
then startweek
else startweek + 1
end as rotation ,
q.weekshiftpatternid,
q.shiftyear
from
(
select locationid,employeeid, left(d, charindex(',', d + ',')-1) as weekshiftpatternid ,
startweek,shiftyear
from (
select *, substring(shiftpattern, number, 200) as d from MyTable locationid left join
(select distinct number from master.dbo.spt_values where number between 1 and 200) col2
on substring(',' + shiftpattern, number, 1) = ','
) t
) q
輸出
+------------+------------+----------+--------------------+-----------+
| locationid | employeeid | rotation | weekshiftpatternid | shiftyear |
+------------+------------+----------+--------------------+-----------+
| 1 | 10000064 | 20 | 1006 | 2016 |
| 1 | 10000064 | 21 | 1008 | 2016 |
| 1 | 10000065 | 20 | 1006 | 2016 |
| 1 | 10000065 | 21 | 1008 | 2016 |
+------------+------------+----------+--------------------+-----------+
很好。完成檢查後,我會標記你的答案。 – Shohel
類似: 在我的測試表我的ID是你EmployeeID
但是還是要解決它。
SELECT
*,
LEFT(shiftBits, CHARINDEX(',', shiftBits + ',')-1) newShiftPattern,
StartWeek+ROW_NUMBER() OVER(PARTITION BY ID ORDER BY shiftBits) as newStartWeek
FROM
(
SELECT
SUBSTRING(shiftPattern, number, LEN(shiftPattern)) AS shiftBits,
test2.*
FROM
test2,master.dbo.spt_values
WHERE
TYPE='P' AND number<LEN(shiftPattern)
AND SUBSTRING(',' + shiftPattern, number, 1) = ','
) AS x
有多少班次模式?這個數字是否一致? – LoztInSpace
它們是固定長度嗎? – LoztInSpace
如果換檔模式是1006,那麼旋轉20和1008旋轉21.我是否讓你正確? –