一个选项使用递归查询:
with cte as (
select
customer,
averageDailyConsumption,
startDate,
case when endDate > eomonth(startDate)
then eomonth(startDate)
else endDate
end endDate,
endDate originalEndDate
from mytable
union all
select
customer,
averageDailyConsumption,
dateadd(day, 1, endDate) startDate,
case when originalEndDate > eomonth(dateadd(day, 1, endDate))
then eomonth(dateadd(day, 1, endDate))
else originalEndDate
end,
originalEndDate
from cte
where originalEndDate > endDate
)
select customer, averageDailyConsumption, startDate, endDate
from cte
order by customer, startDate
Demo on DB Fiddle:
客户 |平均每日消费 |开始日期 |结束日期
--------: | :------------------------ | :--------- | :---------
3 | 578.67 | 2019-10-02 | 2019-10-16
3 | 85.94 | 2019-10-17 | 2019-10-31
3 | 85.94 | 2019-11-01 | 2019-11-30
3 | 85.94 | 2019-12-01 | 2019-12-17
3 | 95.97 | 2019-12-18 | 2019-12-31
3 | 95.97 | 2020-01-01 | 2020-01-31
3 | 95.97 | 2020-02-01 | 2020-02-13
这是 SQL Server eomonth():
with cte as (
select
customer,
averageDailyConsumption,
startDate,
case when endDate > dateadd(month, ((year(startDate) - 1900) * 12) + month(startDate), -1)
then cast(dateadd(month, ((year(startDate) - 1900) * 12) + month(startDate), -1) as date)
else endDate
end endDate,
endDate originalEndDate
from mytable
union all
select
customer,
averageDailyConsumption,
dateadd(day, 1, endDate) startDate,
case when originalEndDate > dateadd(month, ((year(dateadd(day, 1, endDate)) - 1900) * 12) + month(dateadd(day, 1, endDate)), -1)
then cast(dateadd(month, ((year(dateadd(day, 1, endDate)) - 1900) * 12) + month(dateadd(day, 1, endDate)), -1) as date)
else originalEndDate
end,
originalEndDate
from cte
where originalEndDate > endDate
)
select customer, averageDailyConsumption, startDate, endDate
from cte
order by customer, startDate
Demo on DB Fiddle