如何在两个表格中设置日期范围?

时间:2019-10-15 21:44:39

标签: sql

我有两个具有日期的表:date_from和date_to。

我需要以特定的方式加入他们。

表1的范围为2019/05/01-2019/09/30 和tabel2的范围为2019/07/01-2019/08/30

我需要将它们分成3行:

2019/05/01 - 2019/06/30
2019/07/01 - 2019/08/30
2019/09/01 - 2019/09/30

查询

select date_from, date_to, value
from table1
union all
select date_from, date to, value
from table2

输入是:

table1:  
date_from    date_to  
2019/05/01   2019/09/30  

table 2:  
date_from    date_to  
2019/07/01   2019/08/30  

输出应为:

date_from    date_to  
2019/05/01   2019/06/30  
2019/07/01   2019/08/30  
2019/09/01   2019/09/30  

1 个答案:

答案 0 :(得分:0)

如果您使用的是sql server,那么这是一种实现方法

with table1 as(
Select CAST('2019/05/01' as date) date_from , cast('2019/09/30' as date) as date_to
 )
,table2 as
(
 Select CAST('2019/07/01' as date) date_from ,CAST('2019/08/30' AS DATE) date_to
)
,som as (
Select date_from date1 ,DATEADD(month,DATEDIFF(month, -30, date_from), 30) date_to from 
table1 union 
Select date_from ,DATEADD(month,DATEDIFF(month, -30, date_from), 30)from table2 union 
Select DATEADD(month, DATEDIFF(month, 0, date_to), 0),DATEADD(month,DATEDIFF(month, 0, 
date_to), 30)from table1  

) Select * from som

o / p是

date1                       date_to
2019-05-01 00:00:00.000     2019-06-30 00:00:00.000
2019-07-01 00:00:00.000     2019-08-31 00:00:00.000
2019-09-01 00:00:00.000     2019-09-30 00:00:00.000