SQL SUM一些COUNTS

时间:2015-04-02 21:17:52

标签: sql aggregates

如果我有这样的表:

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生成以下输出,我该怎么做?我想总结苹果下不同苹果品种的数量,柑橘类型的数量相同,但其他一切只是一个计数。

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

我尝试使用带有条件的嵌套聚合,但SQL中不支持嵌套聚合,因此我正在寻找其他一些想法。

5 个答案:

答案 0 :(得分:1)

您可以GROUP BY现有的CASE语句,但必须使用派生表(或在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

答案 1 :(得分:0)

您应该在表中添加一个FruitCategory列。

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

然后你可以按FruitCategory分组

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

但最好有一个单独的水果类别表。

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

然后将您的Fruit表格更改为

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

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

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

答案 2 :(得分:0)

我们假设您将苹果添加为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

答案 3 :(得分:0)

我将如何做到这一点。你也可以把FRUIT_LOOKUP作为一个表,但是你不需要,你可以在你的查询中虚拟地创建它:

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

答案 4 :(得分:0)

从DBTable Group By FRUIT

中选择FRUIT,Count(FRUIT)

如果你想订购:)

从DBTable Group选择FRUIT,Count(FRUIT)按水果顺序排列(FRUIT)