我有一个带有列的表:
| School | Room | Period | Class |
期间值可以是以下类型:
1
2
3
1-3
3-4
对于跨越一个以上时段(例如1-3)的类,我需要创建时段1,2,3的记录。因此,基本上再插入2个,并在适当的期间添加一列。
当前状态:
School Room Period Class
Elm High 100 1 Math
Elm High 101 1-3 Eng
所需状态:
School Room Period Class
Elm High 100 1 Math
Elm High 101 1 Eng
Elm High 101 2 Eng
Elm High 101 3 Eng
有什么想法吗?我只能为此使用T-SQL / SQL。
答案 0 :(得分:2)
假设周期只有一位数字,这是使用递归CTE的一种简单方法:
with t as (
select v.*
from (values ('Elm High', 100, '1', 'Math'),
('Elm High', 101, '1-3', 'Eng')
) v(School, Room, Period, Class)
),
cte as (
select school, room, convert(int, left(period, 1)) as period, class, convert(int, right(period, 1)) as period_end
from t
union all
select school, room, period + 1, class, period_end
from cte
where period < period_end
)
select school, room, period, class
from cte
order by school, room, period;
还有一个db<>fiddle。
将其扩展到大于9的时间并不难,但这似乎是一个上学日的很多时间。