我有2张桌子。表A和表B。我需要创建表C。表B是时间序列表,每天有一条记录。我正在使用Azure SQL 我想将行分成每个月,如下所示:
表A
StartDate EndDate
2018-02-12 2019-02-12
表B
Date Day Month Year
2018-01-01 Monday Jan 2018
2018-02-02 Tuesday Feb 2018
:
:
2019-12-31 Tuesday Dec 2019
输出
Table C
StartDate EndDate Month
2018-02-12 2018-02-28 Feb
2018-03-01 2018-03-31 March
:
:
2019-02-01 2019-02-12 Feb
答案 0 :(得分:0)
您可以通过将TableB分组并使用TableA作为过滤器来做到这一点。
select
min(date) as StartDate
,max(date) as EndDate
,Month
from TableB
where date >= (select StartDate from TableA)
and date <= (select EndDate from TableA)
group by Month,Year
当tableB中有更多行时(附加列id
):
select
min(date) as StartDate
,max(date) as EndDate
,Month
,a.id
from TableB b
join TableA a
on b.Date between a.StartDate and a.EndDate
group by id,Month,Year