具有group by子句的多个Aggregate函数

时间:2013-05-31 13:56:06

标签: sql count group-by

我有以下

WorkflowID  FK_UA                DateApprobation
----------- -------------------- -----------------------
1           3                    NULL
2           1                    NULL
3           1                    NULL
4           2                    2013-05-31 09:22:33.000

我要做的是获得一堆聚合字段。

我想获得Approbated工作流程,非Approbated工作流程,所有工作流程

我知道的方式是“DateApprobation”字段为null或是否为值。

问题是,我希望能够通过“FK_UA”对其进行分组,因此我不知道如何使用group by子句有3个聚合函数(COUNT)。

我正在寻找能够实现这一目标的查询,我尝试了几个类似的案例,我找到了它并返回了一些奇怪的值。

我试过了:

SELECT
    FK_UA
,COUNT(WorkflowID) AS TOTAL
,COUNT(CASE when DateApprobation is not null then 1 else 0 end) AS APPROVED
,COUNT(CASE when DateApprobation is null then 1 else 0 end) AS NOT_APPROVED   
FROM Workflow        
GROUP BY
FK_UA

但它总是为所有3个值返回相同的内容!

2 个答案:

答案 0 :(得分:2)

SELECT
    SUM(CASE WHEN [DateApprobation] IS NOT NULL THEN 1 ELSE 0 END) as [Approbated count],
    SUM(CASE WHEN [DateApprobation] IS NULL THEN 1 ELSE 0 END) as [Non-Approbated count],
    COUNT(*) as [Total]
FROM YourTable
GROUP BY FK_UA 

如果我找对你......

答案 1 :(得分:0)

使用COUNT()的标准SQL解决方案

您也可以使用COUNT(),但请确保将不想计算的值转换为aggregate functions do not aggregate NULL values in SQL NULL,而不是0

SELECT
  fk_ua,
  COUNT(WorkflowID) AS total,
  COUNT(CASE WHEN DateApprobation IS NOT NULL THEN 1 END) AS approved,
  COUNT(CASE WHEN DateApprobation IS NULL THEN 1 END) AS not_approved
FROM Workflow        
GROUP BY fk_ua

实际上,您可以进一步提高这一步,因为您已经在计算NOT NULL值:

SELECT
  fk_ua,
  COUNT(WorkflowID) AS total,
  COUNT(DateApprobation) AS approved,
  COUNT(WorkflowID) - COUNT(DateApprobation) AS not_approved
FROM Workflow        
GROUP BY fk_ua

或者:

SELECT fk_ua, total, approved, total - approved AS not_approved
FROM (
  SELECT
    fk_ua,
    COUNT(WorkflowID) AS total,
    COUNT(DateApprobation) AS approved
  FROM Workflow
  GROUP BY fk_ua
) t

对于大型数据集,此可能会稍快一些,因为您的数据库应该能够识别出只有2个不同的COUNT(...)表达式。大多数商业数据库都可以。

使用FILTER的标准SQL解决方案

某些SQL方言,例如PostgreSQL实现标准的FILTER子句,您可以使用该子句使代码更具可读性。您的查询将显示为:

SELECT
  fk_ua,
  COUNT(*) AS total,
  COUNT(*) FILTER (WHERE DateApprobation IS NOT NULL) AS approved,
  COUNT(*) FILTER (WHERE DateApprobation IS NULL) AS not_approved
FROM Workflow        
GROUP BY fk_ua