我在DetailsTbl
:
ID | Day | hours
----------------------------
1 | 14/feb/14 | 8
1 | 15/feb/14 | 8
表格PAssign
如下:
ID | from | to
----------------------------------
1 | 14/feb/14 | 17/feb/14
通过执行存储过程,输出应显示:
ID | from | to | day | Hours
------------------------------------------------
1 | 14/feb/14 | 17/feb/14 | 14/feb/14 | 8
1 | 14/feb/14 | 17/feb/14 | 15/feb/14 | 8
1 | 14/feb/14 | 17/feb/14 | 16/feb/14 | 0
1 | 14/feb/14 | 17/feb/14 | 17/feb/14 | 0
只有从 / 到之间的天的空值应设置为默认值<&39; 0 &#39;
帮助赞赏
答案 0 :(得分:0)
可以使用recursive CTE或Numbers table获取范围并将其展开为多个记录。以下是使用递归CTE的示例:
;with cte as (
select [id], [from], [to], [from] as day from PAssign
union all
select [id], [from], [to], [day]+1 from cte
where [day] < [to]
)
select
cte.id, cte.[from], cte.[to], cte.[day],
coalesce(d.hours, 0) as hours
from cte
left join DetailsTbl d on cte.id = d.id and cte.day = d.day
结果(DEMO)
| ID | FROM | TO | DAY | HOURS |
|----|---------------------------------|---------------------------------|---------------------------------|-------|
| 1 | February, 14 2014 00:00:00+0000 | February, 17 2014 00:00:00+0000 | February, 14 2014 00:00:00+0000 | 8 |
| 1 | February, 14 2014 00:00:00+0000 | February, 17 2014 00:00:00+0000 | February, 15 2014 00:00:00+0000 | 8 |
| 1 | February, 14 2014 00:00:00+0000 | February, 17 2014 00:00:00+0000 | February, 16 2014 00:00:00+0000 | 0 |
| 1 | February, 14 2014 00:00:00+0000 | February, 17 2014 00:00:00+0000 | February, 17 2014 00:00:00+0000 | 0 |
将其转换为存储过程应该非常简单。另请注意,递归CTE使用每个记录生成的一级递归,因此您需要根据需要设置maximum recursion level。