我有以下数据:
Create Table #Temp
(
CallDate DateTime
)
Insert into #Temp
Select '2015-01-01'
Union
Select '2015-01-02'
Union
Select '2015-01-03'
Union
Select '2015-01-04'
Union
Select '2015-01-06'
Union
Select '2015-01-08'
Union
Select '2015-01-09'
Union
Select '2015-01-15'
我想要的是日期范围:
FromDate ToDate
2015-01-01 2015-01-04
2015-01-06 2015-01-06
2015-01-08 2015-01-09
2015-01-15 2015-01-15
答案 0 :(得分:1)
PostgreSQL语法,因为我现在没有办法在SQL Server上进行测试。原理很简单。减去row_number()值的日期是连续日期的常量。您可以对常量进行分组。
with grouped_dates as (
select call_date,
(call_date - (row_number() over (order by call_date) || ' days')::interval)::date as group_date
from temp
)
select min(call_date) as from_date, max(call_date) as to_date
from grouped_dates
group by group_date
order by min(call_date);
from_date to_date -- 2015-01-01 2015-01-04 2015-01-06 2015-01-06 2015-01-08 2015-01-09 2015-01-15 2015-01-15
答案 1 :(得分:0)
如果你有一个数字表,你可以做这样的事情(每个范围都有一个联合),虽然这很麻烦。
SELECT dateadd(day, number-1, '2015-01-01') as FinalDate
FROM numbers
WHERE number <= datediff(day, '2015-01-01', '2015-01-04') + 1
更好的选择可能是UDF(请参阅此处:https://stackoverflow.com/a/1378788/1324019)