Select 在同一个月内至少从两个特定类别购买了一个的客户数

Select count of customers that purchased at least one from two specific categories in the same month

我正在尝试编写一个查询来计算在 2014 年

的同一个月内至少从 order_type=0 和一个 order_type=1 购买了一个的客户

我有两个 table。

订单table有:

orders_category table:

我试过这个查询但没有用,我知道它不完整而且我错过了月份条件!

Select count(user_id) From order
join orders_category
 on order.order_id = orders_category.order_id
Where (order_type=0 or order_type=1)
and extract (year from order.aquisition_date)=2014
group by user_id
having count (case when type_id=0 then null else null end) > 0
and count (case when type_id=1 then null else null end) > 0;

我不知道如何找到在同一个月内至少有 1 个 order_type=0 订单和 1 个 order_type=1 订单的用户。

您可以根据已有的查询使用此查询。但是,我建议您将 table order 的名称更改为 orders,因为 order 是保留字:

select count(distinct user_id)
from   (
    select     user_id, month(aquisition_date) 
    from       orders
    inner join order_category
            on orders.order_id = order_category.order_id
    where      order_type in (0, 1)
    and        year(aquisition_date) = 2014
    group by   user_id, month(aquisition_date)
    having     count(distinct order_type) = 2
) as base

SQL fiddle

我 select 也在子 select 中编辑了月份,因为在分析过程中单独查看该查询的输出会很有趣。