SQL Group By - Generate multiple aggregate columns

2019-05-03 23:08发布

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!

2条回答
\"骚年 ilove
2楼-- · 2019-05-03 23:40

If you have an identifier/key for this table, then you can pivot it like this:

SELECT 
  [Company], 
  [Date], 
  [Y] Count_Y, 
  [N] Count_N
  FROM Company
PIVOT 
  (COUNT([ID]) FOR FLAG IN ([Y],[N])) pvt

Where ID is your identifier for the table Company.

Fiddle with the code here


If you do not have an identifier/key for the table and Company, Date and Flag are the only columns you have, then you can do a PIVOT on the count of the Flag itself like @ConradFrix has suggested in the comments:

SELECT 
  [Company], 
  [Date], 
  [Y] Count_Y, 
  [N] Count_N
  FROM Company
PIVOT 
  (COUNT(FLAG) FOR FLAG IN ([Y],[N])) pvt
查看更多
疯言疯语
3楼-- · 2019-05-03 23:44

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
查看更多
登录 后发表回答