小编典典

计算组内的每个条件

sql

对于每一个独特的GroupId,我想获得的每一个计数IsGreenIsRoundIsLoud条件和行的总数。

样本数据:

-----------------------------------------------------
 id | ItemId | GroupId | IsGreen | IsRound | IsLoud
----+--------+---------+---------+---------+---------
  1 |  1001  |    1    |    0    |    1    |    1
  2 |  1002  |    1    |    1    |    1    |    0
  3 |  1003  |    2    |    0    |    0    |    0
  4 |  1004  |    2    |    1    |    0    |    1
  5 |  1005  |    2    |    0    |    0    |    0
  6 |  1006  |    3    |    0    |    0    |    0
  7 |  1007  |    3    |    0    |    0    |    0

所需结果:

 ----------------------------------------------------------
 GroupId | TotalRows | TotalGreen | TotalRound | TotalLoud
 --------+-----------+------------+------------+-----------
    1    |     2     |     1      |     2      |     1
    2    |     3     |     1      |     0      |     1
    3    |     2     |     0      |     0      |     0

我正在使用以下代码创建表,但我遇到的问题是,如果任何组中的行均不符合该组中没有出现在最终表中的条件之一。完成我想做的最好的方法是什么?

SELECT total.GroupId
     , total.[Count] AS TotalRows
     , IsGreen.[Count] AS TotalGreen
     , IsRound.[Count] AS TotalRound
     , IsLoud.[Count] AS TotalLoud
FROM (
    SELECT GroupId
         , count(*) AS [Count]
    FROM TestData
    GROUP BY GroupId
) TotalRows
INNER JOIN (
    SELECT GroupId
         , count(*) AS [Count]
    FROM TestData
    WHERE IsGreen = 1
    GROUP BY GroupId
) IsGreen ON IsGreen.GroupId = TotalRows.GroupId
INNER JOIN (
    SELECT GroupId
         , count(*) AS [Count]
    FROM TestData
    WHERE IsRound = 1
    GROUP BY GroupId
) IsRound ON IsRound.GroupId = TotalRows.GroupId
INNER JOIN (
    SELECT GroupId
         , count(*) AS [Count]
    FROM TestData
    WHERE IsLoud = 1
    GROUP BY GroupId
) IsLoud ON IsLoud.GroupId = TotalRows.GroupId

阅读 172

收藏
2021-04-22

共1个答案

小编典典

您可以用来count对每个行进行计数[GroupId]sum计算每个属性。

select [GroupId]
     , count([GroupId]) as [TotalRows]
     , sum([IsGreen]) as [TotalGreen]
     , sum([IsRound]) as [TotalRound]
     , sum([IsLoud]) as [TotalLoud]
from [TestData]
group by [GroupId]
2021-04-22