【问题标题】:SQL split consumption full MonthSQL拆分消费满月
【发布时间】:2020-08-05 16:36:04
【问题描述】:

我有问题。我想拆分一个整月的值。

我有示例中的每日消耗量以及开始和结束日期:

我想像这样在开始日期和结束日期之间拆分每个月的值:

我需要这样做以便每月进行一些计算。

【问题讨论】:

  • 您需要什么帮助?你在问什么?您尝试过什么,为什么没有成功?请务必向我们提出问题,以便我们给您答复。此外,请务必花时间以表格格式text 提供样本数据和结果。它真的可以帮助我们帮助您。
  • 最好以文本(而非图像)形式发布示例数据和所需结果。

标签: sql sql-server tsql date recursive-query


【解决方案1】:

一个选项使用递归查询:

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

【讨论】:

  • 您好 GMB,感谢您的回答。我试过你的例子,我有问题,因为我使用的是 SQL Server 2008 R2 并且函数 EOMONTH() 不可用。
  • 我想创建一个 DataRange,但我不知道该怎么做
  • @Cambrix:我为不支持eomonth() 的 SQL Server 版本更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-07
  • 2019-12-31
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多