I would like to group by Company & Date and generate count columns for 2 separate values (Flag=Y and Flag=N). Input table looks like this:
Company Date Flag
------- ------- -----
001 201201 Y
001 201201 N
001 201202 N
001 201202 N
001 201202 Y
The output should look like this:
Company Date Count_Y Count_N
------- ------ ------- -------
001 201201 1 1
001 201202 1 2
How can I write the SQL query? Any kind of help is appreciated! Thanks!
You can do it using correlated subqueries like this:
SELECT
Company,
Date,
(SELECT COUNT(*) FROM MyTable AS T1
WHERE T1.Flag='Y' AND T1.Company=T2.Company AND T1.Date=T2.Date) AS Count_Y,
(SELECT COUNT(*) FROM MyTable AS T1
WHERE T1.Flag='N' AND T1.Company=T2.Company AND T1.Date=T2.Date) AS Count_N
FROM MyTable AS T2
GROUP BY Company, Date
You can also do it more concisely, but perhaps with (arguably) slighly less readability using the SUM
trick:
SELECT
Company,
Date,
SUM(CASE WHEN Flag='Y' THEN 1 ELSE 0 END) AS Count_Y,
SUM(CASE WHEN Flag='N' THEN 1 ELSE 0 END) AS Count_N,
FROM MyTable
GROUP BY Company, Date
In Oracle/PLSQL, the DECODE
function can be used to replace the CASE
for the even more concise:
SELECT
Company,
Date,
SUM(DECODE(Flag,'Y',1,0)) AS Count_Y,
SUM(DECODE(Flag,'N',1,0)) AS Count_N,
FROM MyTable
GROUP BY Company, Date
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With