我有一个记录看起来如下做单记录多个记录在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.我是否让你正确? –