我需要汇总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 = 10
July,2016
和August,2016
中有Invoice_date的人Amount
。我需要在特定日期范围内分别对7月和8月份该特定客户的所有付款进行总结。但是我从上面的努力中得到Invoice_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
的总和。
期望的输出:
true
我怎么能克服这个?任何帮助将不胜感激。
答案 0 :(得分: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;
答案 1 :(得分:2)
你差不多完成了。只需将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 ;