使用子查询获取行计数

时间:2014-04-30 00:49:35

标签: mysql count subquery

我目前正在使用外部查询的子查询来获取在特定时间内订购图书的人数。我是那里的一部分。我当前的子查询是:

select count(cust_id)
from a_bkorders.order_headers
where date_format(order_date,'%Y/%m') = Prevmonth(curdate(),1)
or date_format(order_date,'%Y/%m') = PrevMonth(curdate(),2)
group by cust_id;

返回

count(cust_id)
1
1
1
1
1
1
1
1
2
2
2
4
14

我想要计算返回的行数是13,但我不认为围绕count()中的整个子查询将会有所作为。我确定这是一个简单的解决方案,但我没有看到它。 感谢。

(PrevMonth是我写的一个函数)

2 个答案:

答案 0 :(得分:3)

我认为你只想要count(distinct)而不是count()

select count(distinct cust_id)
from a_bkorders.order_headers
where date_format(order_date,'%Y/%m') = Prevmonth(curdate(),1) or
      date_format(order_date,'%Y/%m') = PrevMonth(curdate(),2);

答案 1 :(得分:1)

你应该能够只计算返回的结果。不确定这是否会导致您的外部查询出现问题,但如果您想发布一些示例数据,我可以构建一个小提琴并快速修复它。

SELECT 
    COUNT(first_count) -- first_count is the alias i gave the subquery count. so its a count of the number of rows returned in the subquery's count
FROM(
    SELECT 
        COUNT(cust_id) AS first_count
    FROM a_bkorders.order_headers
    WHERE date_format(order_date,'%Y/%m') = Prevmonth(curdate(),1)
        OR date_format(order_date,'%Y/%m') = PrevMonth(curdate(),2)
    GROUP BY cust_id
) AS temp; -- all tables need to have an alias

您可能甚至不想在子查询中计算...除非您需要这些客户订购的书籍数量。您可以SELECT COUNT(DISTINCT cust_id) FROM....获取唯一ID的数量。