COUNT和COUNT,GROUP BY第一计数

时间:2019-07-31 21:10:34

标签: mysql sql

我正在尝试通过订单数来吸引客户。我能够同时提取订单数和具有订单数的客户数,但是当订单数相同时,我无法获得客户数的总和。

SELECT COUNT(orderid) AS ordrs, 
       CASE WHEN COUNT(orderid)=COUNT(orderid) THEN COUNT(DISTINCT(custid)) ELSE "NA" END AS customr_cnt 
FROM orders;

我也尝试过跑步

SELECT COUNT(orderid) AS ordrs, 
       CASE WHEN COUNT(orderid)=COUNT(orderid) THEN COUNT(custid) ELSE "NA" END AS customr_cnt 
FROM orders;

哪个会同时返回订单总数和客户总数

1 个答案:

答案 0 :(得分:2)

  

我正在尝试通过订单数来吸引客户。

您想要两个层次的聚合吗?

select num_orders, count(*)
from (select custid, count(*) as num_orders
      from orders
      group by custid
     ) o
group by num_orders
order by num_orders;