5

我有以下

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

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

我想获得批准的工作流程、未批准的工作流程、所有工作流程

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

问题是,我希望能够通过“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 个值返回相同的东西!

4

2 回答 2

3
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 

如果我没听错的话......

于 2013-05-31T14:03:46.323 回答
1

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

您也可以使用COUNT(),但请确保将您不想计入的值转换为NULL, not 0,因为聚合函数不会NULL在 SQL 中聚合值

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(...)表达式。大多数商业数据库都可以。

使用标准 SQL 解决方案FILTER

一些 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
于 2020-05-07T18:43:15.990 回答