Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Group By - Generate multiple aggregate columns from single column

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!

like image 912
Thracian Avatar asked Sep 10 '12 20:09

Thracian


1 Answers

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
like image 190
Michael Goldshteyn Avatar answered Oct 13 '22 17:10

Michael Goldshteyn