需要按开始年份和之后每年分组的事实行的总和

时间:2016-03-16 06:04:00

标签: mysql sql sql-server

我有两张桌子:

  • customers表,列customer_idcreated_at
  • orders表,包含order_id列,customer_idpaid_atamount

我必须编写一个SQL查询,根据他们注册的年份(他们的队列年份)分解客户,并确定多年来每个队列的年度总收入(例如,2011年的队列总收入为第1年$ x,第2年$ y等。)

select c.customer_id, c.created_at, SUM(o.amount) as Tot_amt
from customers c inner join orders o on c.customer_id = o.customer_id
group by c.created_at, Tot_amt;

3 个答案:

答案 0 :(得分:0)

GROUP BY年(日期栏)

select   c.customer_id, YEAR(c.created_at), SUM(o.amount) as Tot_amt
from     customers c inner join orders o on c.customer_id = o.customer_id
group by c.customer_id, YEAR(c.created_at)

答案 1 :(得分:0)

由于它是客户的分手,customer_id在最终输出中毫无意义,只有队列年代才会出现问题。

select YEAR(c.created_at), SUM(o.amount) as Tot_amt
from customers c inner join orders o using(customer_id)
group by YEAR(c.created_at);

答案 2 :(得分:0)

支持你的陈述

  

2011年队列的第1年总收入为$ x,第2年为$ y

您的订单表中应该有orderDate

select 
  YEAR(c.created_at) as cohortYear, 
(YEAR(orderDate)-YEAR(c.created_at)+1) as YearNum,
SUM(o.amount) OVER( PARTITION by YEAR(c.created_at),(YEAR(orderDate)-YEAR(c.created_at)) ORDER BY YEAR(c.created_at),(YEAR(orderDate)-YEAR(c.created_at))) as Tot_amt
from customers c inner join orders o on c.customer_id = o.customer_id

如果您需要使用分组

的解决方案
select 
  YEAR(c.created_at) as cohortYear, 
(YEAR(orderDate)-YEAR(c.created_at)+1) as YearNum,
SUM(o.amount) as Tot_amt
from customers c inner join orders o on c.customer_id = o.customer_id
group by YEAR(c.created_at),(YEAR(orderDate)-YEAR(c.created_at)+1)
order by YEAR(c.created_at),(YEAR(orderDate)-YEAR(c.created_at))