Sunday, February 26, 2012

group by and count

I want to know how to merge the following data. I am using 4 queries below. I was hoping to do it with 1 query.
Table1
Dist Fund
VAE AO
VAW AO
MD Court
MD Judge
CAC AO
CAC Court
VAE Judge
VAE Judge
I want to join the following 3 queries:
DcountAll DcountAO
Select Dist, Count(Dist)as Count from Table1 GROUP BY Table1.Dist Select Dist, Count(Dist) as Count from Table1 Where Dist='AO' GROUP BY Table1.Dist

DcountCourt
Select Dist, Count(Dist) as Count from Table1 Where Dist='Court' GROUP BY Table1.Dist

SELECT DCountAll.Dist, DCountAll.Count, DcountAO.Count AS AO, DcountCourt.Count
FROM DcountCourt RIGHT JOIN (DcountAO RIGHT JOIN DCountAll ON DcountAO.Dist = DCountAll.Dist) ON DcountCourt.Dist = DCountAll.Dist;

I'm not quite sure what you are wanting to see in your result set. The first query will return all unique Dist with a count for each. The second query returns the name and count only for "AO", and the third returns the count only for "Court".

The first query would already contain the results from queries 2 and 3. I don't quite understand the 4th query.

|||

Benefit from the fact that NULLs are excluded from aggregates

SELECT COUNT(*) as AllCount,COUNT(CASE WHEN Dist='AO' THEN 1 ELSE NULL) AS AOCount,COUNT(CASE WHEN Dist='Court' THEN 1 ELSE NULL) AS CourtCount FROM Table1

No comments:

Post a Comment