SQL Group By - 从单列生成多个聚合列

时间:2012-09-10 20:36:13

标签: sql-server sql-server-2008 count grouping aggregate

我想按公司和公司分组。日期并为2个单独的值生成计数列(Flag = Y和Flag = N)。 输入表如下所示:

Company  Date   Flag
------- ------- -----
001      201201  Y
001      201201  N
001      201202  N
001      201202  N
001      201202  Y

输出应如下所示:

Company Date   Count_Y Count_N
------- ------ ------- -------
001     201201  1       1
001     201202  1       2

如何编写SQL查询? 任何形式的帮助表示赞赏!谢谢!

2 个答案:

答案 0 :(得分:12)

您可以使用相关的子查询来执行此操作:

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

你也可以更简洁地做到这一点,但也许(可以说)使用SUM技巧的可读性稍差:

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

在Oracle / PLSQL中,可以使用DECODE函数替换CASE以获得更简洁:

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

答案 1 :(得分:2)

如果您有此表的标识符/密钥,则可以像这样进行透视:

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

ID是表格Company的标识符。

摆弄代码here


如果您没有表格和公司的标识符/密钥,日期和标记是您拥有的唯一列,那么您可以对PIVOT本身的计数Flag进行SELECT [Company], [Date], [Y] Count_Y, [N] Count_N FROM Company PIVOT (COUNT(FLAG) FOR FLAG IN ([Y],[N])) pvt @ConradFrix在评论中建议:

{{1}}