对sql server中的多条记录进行单条记录

时间:2016-05-19 04:22:21

标签: sql sql-server

我的记录如下所示

enter image description here

从两行开始,我想分割ShiftPattern值并创建多个记录,并按顺序创建StartWeek。

最终查询:

  1. 拆分ShiftPattern列并创建多个记录
  2. 将StartWeek添加为20,21轮换。
  3. 输出结果

    enter image description here

2 个答案:

答案 0 :(得分: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 |
+------------+------------+----------+--------------------+-----------+

答案 1 :(得分: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