这是我正在使用的桌子:
customer_id order_id order_date
101 1 2016-12-11
102 2 2016-12-13
101 3 2017-12-14
103 4 2017-12-15
... ... ...
我需要一个SQL来找出在2016年和2017年有多少客户购买了X次以上的商品。
我已经得到了正确的答案,它是客户101,使用以下代码:
select
customer_id
from
(
select
year(order_date) as order_date_year,
customer_id,
count(*) as number_of_orders
from
cust_orders
group by
year(order_date),
customer_id
having
count(*) >= 3
) as t
group by
order_date_year,
customer_id
但是这并不能解决特定年份超过X的问题。
感谢您的任何帮助,谢谢!
您需要2级汇总:
select c.customer_id
from (
select customer_id
from cust_orders
where year(order_date) in (2016, 2017)
group by customer_id, year(order_date)
having count(*) >= 10
) c
group by c.customer_id
having count(*) = 2;
用购买数量代替10
。将2
更改为要搜索的年数。参见demo。
您可以将聚合与having
子句一起使用,以按年份和客户获取计数。然后再次汇总并计算年份:
select customer_id
from (select customer_id, year(order_date) as year
from cust_orders co
group by customer_id, year(order_date)
having count(*) >= X
) x
where year in (2016, 2017)
group by customer_id
having count(*) = 1;