如何编写SQL查询来找出每年每月至少购买两次的客户

时间:2018-12-21 17:57:20

标签: sql sql-server

我有一个表,其中包含order_id,customer_id,order_date和Amount列。

enter image description here

如何查找一年中每月(从1月到12月)至少订购2次的客户?

1 个答案:

答案 0 :(得分:5)

我认为您正在寻找类似的东西

select
    order_date_year,
    customer_id
from 
(
    select  
        year(order_date) as order_date_year,
        month(order_date) as order_date_month,
        customer_id,
        count(*) as number_of_orders
    from
        tableName
    group by
        year(order_date),
        month(order_date),
        customer_id
    having
        count(*) >= 2
) as t
group by
    order_date_year,
    customer_id
having
    count(*) = 12