我有两张桌子:
customers
表,列customer_id
,created_at
orders
表,包含order_id
列,customer_id
,paid_at
,amount
我必须编写一个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;
答案 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))