gillweb
gillweb

Reputation: 91

How can i nest another SQL COUNT into this?

I have this code that works as planned. Gives me the "source" and how many apps for each source.

SELECT source, COUNT(1) as Cnt
    FROM apps
    WHERE monthyear = 'October2018' 
    GROUP BY source

OUTPUT is ['Store1', 1], ['Store2', 5], ['Store3', 3],

I have another row named "sold" on the same table that i would like to count within each Store of how many sold = 1 so i get this output:

Source, Apps, Sold ['Store1', 1, 0], ['Store2', 5, 3], ['Store3', 3, 1]

Upvotes: 1

Views: 84

Answers (1)

Joe Farrell
Joe Farrell

Reputation: 3542

If I'm understanding you correctly, then you have a column in the apps table called sold which is presumably a Boolean value, and you want your existing query to return the number of records for each distinct source value for which the sold flag is set. In that case you need a conditional count, like so:

select
    source,
    count(1) as Cnt,
    count(case when Sold = 1 then 1 end) as CountSold
from
    apps
where
    monthyear = 'October2018' 
group by
    source;

Then you just update your code to include the new CountSold value wherever you want it. Let me know if I've misunderstood your question.

Upvotes: 2

Related Questions