views:

19

answers:

1

We have a table like below in an sql server 2005 db:

event_id   staff_id   weeks

1          1          NNNYYYYNNYYY
1          2          YYYNNNYYYNNN
2          1          YYYYYYYYNYYY

This is from a piece of timetabling software and is basically saying which staff members are assigned to an event (register) and the set of weeks they are teaching that register. So staff_id 1 isn't teaching the first 3 weeks of event 1 but is teaching the following 4....

Is there an easy way to convert that to an easier form such as:

event_id   staff_id   week
1          1          4
1          1          5
1          1          6
1          1          7
1          1          10
1          1          11
1          1          12
1          2          1
1          2          2
1          2          3
1          2          7
1          2          8
1          2          9
2          1          1
2          1          2
2          1          3
2          1          4
2          1          5
2          1          6
2          1          7
2          1          8
2          1          10
2          1          11
2          1          12
+3  A: 
WITH cte AS
(
    SELECT 1 AS [week]
    UNION ALL
    SELECT [week] + 1
    FROM cte
    WHERE [week] < 53
)
SELECT t.event_id, t.staff_id, cte.[week]
FROM your_table AS t
    INNER JOIN cte
        ON LEN(ISNULL(t.weeks, '')) >= cte.[week]
            AND SUBSTRING(t.weeks, cte.[week], 1) = 'Y'
ORDER BY t.event_id, t.staff_id, cte.[week]
LukeH
That's brilliant thanks I knew there would be a way
PeteT