Mysql 选择当月从两个特定类别中至少购买一个的客户计数

Mysql 选择当月从两个特定类别中至少购买一个的客户计数,mysql,join,Mysql,Join,我正在尝试编写一个查询,以统计2014年同一个月内至少从订单类型=0和一个订单类型=1购买了一个的客户 我有两张桌子 订单表格包含: 订单号 客户识别码 采集日期 订单\u类别表格: 订单号 订单类型(订单类型可能有0、1、2、3、5、8…等) 我尝试了这个查询,但它没有工作,我知道它不完整,我错过了一个月的条件 Select count(user_id) From order join orders_category on order.order_id = orders_catego

我正在尝试编写一个查询,以统计2014年同一个月内至少从
订单类型=0
和一个
订单类型=1
购买了一个的客户

我有两张桌子

订单表格包含:

  • 订单号
  • 客户识别码
  • 采集日期
订单\u类别表格:

  • 订单号
  • 订单类型(订单类型可能有0、1、2、3、5、8…等)
我尝试了这个查询,但它没有工作,我知道它不完整,我错过了一个月的条件

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;

我不知道如何在同一个月内从
order\u type=0
order\u type=1
中找到至少有1个订单的用户。

根据您已有的订单,您可以使用此查询。但是,我建议您将表名
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


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

我看不出您希望您的两个案例语句做什么;大小写的两边都是NULL,因此它们永远不能大于0,因此永远不会有一行的计数匹配。阅读您写的内容:
count(当type\u id=0时为空,否则为空结束)
。那怎么会返回大于0的值呢?你真是个天才!非常感谢:D@trincot