【问题标题】:Aggregate multiple columns based on specific date range with in a month根据一个月内的特定日期范围聚合多个列
【发布时间】:2016-08-04 04:52:25
【问题描述】:

我需要聚合 Amounts 以每月按日期范围显示。为了说明,请看下表:

Invoice_Payment

Customer_id    Invoice_no    Invoice_date    Amount
---------------------------------------------------
10             10023         2016-07-08      60
10             10018         2016-08-04      90
11             10016         2016-07-01      110
11             10021         2016-07-05      120
12             10028         2016-07-11      10
12             10038         2016-07-31      5

您会注意到,我想根据Customer_id 对它们进行分组并显示从开始到结束的日期。此外,这必须仅针对每个月进行。

到目前为止我已经尝试过以下查询:

select Customer_id, (mindate + ' to ' + maxdate) Date_Range, Amount
from (
     select Customer_id, sum(Amount) Amount, min(Invoice_date) mindate, max(Invoice_date) maxdate  
     from Invoice_Payment
     group by Customer_id
     ) I ; 

从上面的查询我得到Output 喜欢:

Customer_id    Date_Range                    Amount
10             2016-07-08 to 2016-08-04      150
11             2016-07-01 to 2016-07-05      230
12             2016-07-11 to 2016-07-31      15

请检查这个.. SQL Fiddle Working Demo

假设Customer_id = 10July,2016August,2016 中有Invoice_date。我需要在特定日期范围内分别汇总该特定客户在 7 月和 8 月的所有付款。但我从上述努力中得到了所有Invoice_date 中的Amount 的总和。

期望的输出:

Customer_id    Date_Range                    Amount
10             2016-07-08 to 2016-07-08      60
10             2016-08-04 to 2016-08-04      90
11             2016-07-01 to 2016-07-05      230
12             2016-07-11 to 2016-07-31      15

我怎么能克服这个?任何帮助将不胜感激。

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    你快完成了。只需将YEARMONTH 添加到GROUP BY

    select Customer_id, (mindate + ' to ' + maxdate) Date_Range, Amount
    from (
           select Customer_id, 
           sum(Amount) Amount, min(Invoice_date) mindate, max(Invoice_date) maxdate  
           from #Invoice_Payment
    group by 
      Customer_id,
      YEAR(Invoice_date),
      MONTH(Invoice_date)
    ) I ;
    

    【讨论】:

      【解决方案2】:

      按customer_id、月份和年份分组怎么样

      select Customer_id, (mindate + ' to ' + maxdate) Date_Range, Amount
      from (
             select Customer_id, 
             sum(Amount) Amount, min(Invoice_date) mindate, max(Invoice_date) maxdate  
             from #Invoice_Payment
             group by Customer_id,month(Invoice_date), year(Invoice_date)
      ) I
      order by customer_id;
      

      【讨论】:

        猜你喜欢
        • 2016-02-12
        • 1970-01-01
        • 2014-06-04
        • 2019-05-30
        • 2018-02-03
        • 2021-12-05
        • 1970-01-01
        • 2018-01-09
        • 2021-04-16
        相关资源
        最近更新 更多