2016-05-19 48 views
4

我有一个记录看起来如下做单记录多个记录在SQL Server

enter image description here

从两排,我想分裂ShiftPattern值,并创建多个记录,并StartWeek将依次产生。

最终查询:

  1. 拆分ShiftPattern柱和创建多个记录
  2. 增加StartWeek像20,21旋转。

输出结果

enter image description here

+0

有多少班次模式?这个数字是否一致? – LoztInSpace

+0

它们是固定长度吗? – LoztInSpace

+0

如果换档模式是1006,那么旋转20和1008旋转21.我是否让你正确? –

回答

2

这是你所需要的。在小提琴测试。

SQLFiddle Demo

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 | 
+------------+------------+----------+--------------------+-----------+ 
+0

很好。完成检查后,我会标记你的答案。 – Shohel

1

类似: 在我的测试表我的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