2

I'm trying to count all the "Y"s and "N"s in one column but group them by another column. I can get it to pull just the "Y" or the "N" with a WHERE:

SELECT TABLE2.GROUP_BY_THIS,COUNT(TABLE1.FLAG)
FROM TABLE1 INNER JOIN
TABLE2 On TABLE1.Primary_Key = TABLE2.Foreign_Key
WHERE TABLE1.FLAG_Required = "Y"
GROUP BY TABLE2.GROUP_BY_THIS

and I can see the "Y"s and "N"s for the whole data set and not grouped by the other column using the first answer here: SQL - Counting a column twice but I'm not too sure how to get my desired outcome which should look a little like this:

GROUP_BY_THIS  Y COUNT  N COUNT
-------------------------------
GROUP1         10       1
GROUP2         10       100
GROUP3         0        10
GROUP4         50       500
GROUP5         1000     0

Do I need a further grouping somehow?

Community
  • 1
  • 1
ydaetskcoR
  • 53,225
  • 8
  • 158
  • 177

1 Answers1

4
SELECT  TABLE2.GROUP_BY_THIS
,       COUNT(CASE WHEN TABLE1.FLAG = 'Y' THEN 1 END)
,       COUNT(CASE WHEN TABLE1.FLAG = 'N' THEN 1 END)
FROM    TABLE1 
JOIN    TABLE2 
ON      TABLE1.Primary_Key = TABLE2.Foreign_Key
GROUP BY 
        TABLE2.GROUP_BY_THIS
Andomar
  • 232,371
  • 49
  • 380
  • 404