繁体   English   中英

MySQL count()查询返回行而不是total?

[英]MySQL count() query returns rows instead of total?

这个查询可能有什么问题:

select count(customer_email) as num_prev
  from _pj_cust_email_by_date
  where order_date < '2011-02'
  and customer_email is not null
  group by customer_email having count(order_date) > 0;

返回行结果,例如:

1
2
3
2
1
5
4

当我想要计算在指定日期范围内购买的客户总数的完整数量

_pj_cust_email_by_date是一个仅以YYYY-MM-DD格式返回电子邮件地址和订单日期的视图。 我无权使用除此视图之外的任何内容。

GROUP BY引起了这种情况。

它会导致每个组返回一个结果行,在此为customer_email每个不同值返回。

如果您需要不同电子邮件地址的总数,则需要删除GROUP BY子句并将COUNT更改为COUNT(DISTINCT customer_email)

你需要进一步查询它

select count(*) CustomerCount
from (
    select count(customer_email) as num_prev
    from _pj_cust_email_by_date
    where order_date < '2011-02'
    and customer_email is not null
    group by customer_email having count(order_date) > 0;
) as innercount

这通常是方法,但由于你使用having count(order_date) > 0 ,我认为你只需要

select count(distinct customer_email) as num_prev
from _pj_cust_email_by_date
where order_date < '2011-02' and customer_email is not null

因为HAVING子句永远不会用空的order_dates来详细说明,这实际上使得HAVING子句变成了哑弹

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM