我需要汇总Amounts以按每月的日期范围显示。为了说明这一点,请看下表:
发票支付
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
Run Code Online (Sandbox Code Playgroud)
您会注意到,我想根据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 ;
Run Code Online (Sandbox Code Playgroud)
从上面的查询我得到的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
Run Code Online (Sandbox Code Playgroud)
请检查这个..SQL Fiddle Working Demo
假设谁在和Customer_id = 10中有 Invoice_date 。我需要分别汇总该特定客户在特定日期范围内 7 月和 8 月的所有付款。但我从上述努力中得到了所有的总和。July,2016August,2016AmountInvoice_date
期望的输出:
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
Run Code Online (Sandbox Code Playgroud)
我怎样才能克服这个困难呢?任何帮助将不胜感激。
你快完成了。只需添加YEAR和MONTH即可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 ;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
357 次 |
| 最近记录: |