9

我想按公司和日期分组并为 2 个单独的值(标志 = Y 和标志 = 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 查询?任何形式的帮助表示赞赏!谢谢!

4

2 回答 2

19

您可以使用这样的相关子查询来做到这一点:

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
于 2012-09-10T20:46:04.250 回答
3

如果你有这个表的标识符/键,那么你可以像这样旋转它:

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

ID表的标识符在哪里Company

在这里摆弄代码


如果您没有表的标识符/键,并且 Company、Date 和 Flag 是您拥有的唯一列,那么您可以像@ConradFrix 在评论中建议的那样PIVOT对自身进行计数:Flag

SELECT 
  [Company], 
  [Date], 
  [Y] Count_Y, 
  [N] Count_N
  FROM Company
PIVOT 
  (COUNT(FLAG) FOR FLAG IN ([Y],[N])) pvt
于 2012-09-10T21:01:52.933 回答