Question

im currently using a subquery of an outer query to get the number of people who ordered a book ina certain time. Im a part of the way there. My current subquery is:

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;

which returns

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

I want a count of the rows returned which is 13 but i dont think surrounding the entire subquery in count() is going to do the trick. Im sure this is an easy fix but im not seeing it. Thanks.

(PrevMonth is a function i have written)

Was it helpful?

Solution 2

you should be able to just do a count of the returned results. Not sure if this will cause problems with your outer query, but if you want to post that with some sample data I can build a fiddle and fix it up real quick.

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

you may not even want to do a count in your subquery... unless you need the number of books that those customers ordered as well. you could just SELECT COUNT(DISTINCT cust_id) FROM.... to get the number of unique id's.

OTHER TIPS

I think you just want count(distinct) rather than 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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top