SQL 对一些计数求和

SQL SUM some COUNTS

如果我有这样的table:

FRUIT
------------------------
GRANNY SMITH
BANNANA
CHERRY
RED DELICIOUS
DURIAN
FIG
GRAPE
LIME
ORANGE
BRAEBURN
TANGERINE
GRANNY SMITH
ORANGE
ORANGE
GRANNY SMITH
LIME
FIG
FIG
GRANNY SMITH
BRAEBURN

我想使用 SQL 生成以下输出,我该怎么做?我想把apple下不同苹果品种的数量加起来,柑橘类也一样,但其他的都只是一个数量。

FRUIT       COUNT
----------- ------
APPLE       7
BANNANA     1
CHERRY      1
CITRUS      6
DURIAN      1
FIG         3
GRAPE       1

我尝试使用带条件的嵌套聚合,但 SQL 不支持嵌套聚合,所以我正在寻找其他想法。

您应该将 FruitCategory 列添加到您的 table。

Fruit          FruitCategory
----------------------------
GRANNY SMITH   APPLE
BANNANA        BANNANA
BRAEBURN       APPLE
...

然后可以按水果分类分组

SELECT FruitCategory, COUNT(*) AS [Count]
FROM tblFruit
GROUP BY FruitCategory
ORDER BY FruitCategory

不过水果单独分类比较好table.

FruitCategoryID FruitCategory
-----------------------------
1               Apple
2               Banana
...

然后把你的水果table改成

Fruit          FruitCategoryID
------------------------------
GRANNY SMITH   1
BANNANA        2
BRAEBURN       1
...

这允许您使用类别 table 作为组合框等的查找,并使其更健壮,因为将类别名称直接写入水果 table 很容易出错。

SELECT
    c.FruitCategory, COUNT(*) AS [Count]
FROM
    tblFruit f
    INNER JOIN tblFruitCategory c
        ON f.FruitCategoryID = c.FruitCategoryID
GROUP BY
    f.FruitCategoryID
ORDER BY
    c.FruitCategory

假设您将苹果添加为 type=1,将柑橘类水果添加为 type=2,将其他水果添加为 type=3(列为 Type) ), 然后就这样做 -

select CASE Type WHEN 1 THEN APPLE ELSE CITRUS, count(*) as COUNT
from table
where Type in (1,2)
group by Type
union all
select FRUIT, count(*) as COUNT
from table
where Type = 3
group by FRUIT

这是我的做法。您也可以将 FRUIT_LOOKUP 设为 table,但您不需要,您可以像这样在查询中虚拟地制作它:

WITH FRUIT_LOOKUP AS
(
   SELECT 'GRANNY SMITH' AS FRUIT, 'APPLE' AS FTYPE
   UNION ALL
   SELECT 'BANNANA' AS FRUIT, 'BANNANA' AS FTYPE
   UNION ALL
   SELECT 'CHERRY' AS FRUIT, 'CHERRY' AS FTYPE
   UNION ALL
   SELECT 'RED DELICIOUS' AS FRUIT, 'APPLE' AS FTYPE
   UNION ALL
   SELECT 'DURIAN' AS FRUIT, 'DURIAN' AS FTYPE
   UNION ALL
   SELECT 'FIG' AS FRUIT, 'FIG' AS FTYPE
   UNION ALL
   SELECT 'GRAPE' AS FRUIT, 'GRAPE' AS FTYPE
   UNION ALL
   SELECT 'LIME' AS FRUIT, 'CITRUS' AS FTYPE
   UNION ALL
   SELECT 'TANGERINE' AS FRUIT, 'CITRUS' AS FTYPE
   UNION ALL
   SELECT 'BRAEBURN' AS FRUIT, 'APPLE' AS FTYPE
   UNION ALL
   SELECT 'ORANGE' AS FRUIT, 'CITRUS' AS FTYPE
)
SELECT FL.FTYPE AS FRUIT, COUNT(*) AS COUNT
FROM FRUITTABLE F
JOIN FRUIT_LOOKUP FL ON F.FRUIT = FL.FRUIT
GROUP BY FL.FTYPE

Select FRUIT,来自 DBTable 的计数(FRUIT)按 FRUIT 分组

如果您想订购:)

Select FRUIT,Count(FRUIT) from DBTable Group By FRUIT Order by Count(FRUIT)

您可以 GROUP BY 您现有的 CASE 语句,但您必须使用 Derived Table(或在 GROUP BY 中重复那个巨大的 CASE):

select FRUIT, COUNT(*)
from 
 (
   select CASE 
             WHEN FRUIT IN ('GRANNY SMITH', 'RED DELICIOUS', ...) THEN 'APPLE'
             WHEN FRUIT IN ('ORANGE', 'TANGERINE', ...) THEN 'CITRUS'
             ELSE FRUIT
          END AS FRUIT
   from tab
 ) dt
group by FRUIT
order by FRUIT