【问题标题】:SQL count occurrences of certain categories that rows belong toSQL 计算行所属的某些类别的出现次数
【发布时间】:2012-11-05 18:29:15
【问题描述】:

我有这张表,里面有一些数据:

table ColorsFlavors

id | name | color | flavor
--------------------------
 1 | n1   | green | lemon
 2 | n2   | blue  | strawberry
 3 | n3   | red   | lemon
 4 | n4   | green | lemon
 5 | n5   | green | mango
 6 | n6   | red   | chocolate
 7 | n7   | white | lemon
 8 | n8   | blue  | mango
 9 | n9   | green | chocolate

我希望创建一个 SQL 查询(或多个查询?),让我获得每种颜色的总行数,以及每种风格的总行数。

类似这样的:

colors | occurrences
--------------------
green  |   4
blue   |   2
red    |   6
white  |   1


flavor    | occurences
----------------------
lemon     |   4
strawberry|   1
mango     |   2
chocolate |   2

嗯,如果我有一个预定义的颜色和风味列表可供选择,那么数据表上未出现的颜色/风味的计数为 0,那该怎么办?

colors | occurrences
--------------------
green  |   4
blue   |   2
red    |   6
white  |   1
black  |   0


flavor    | occurences
----------------------
lemon     |   4
strawberry|   1
mango     |   2
chocolate |   2
cherry    |   0

那么,检索这些的 SQL 查询是什么?

【问题讨论】:

    标签: sql count group-by


    【解决方案1】:

    对 ColorsFlavors 表中的所有颜色进行处理

    Select
      cf.Color,
      Count(*)
    From
      ColorsFlavors cf
    Group By
      cf.Color
    

    如果您在表格中有一个预定义的列表(我将其称为颜色),并且您希望包含零:

    Select
      c.Color,
      Coalesce(Count(*), 0)
    From
      Colors c
        Left Outer Join
      ColorsFlavors cf
        On c.Color = cf.Color
    Group By
      c.Color
    

    如果你有一个预定义的列表,有人输入了

    Select
      c.Color,
      Coalesce(Count(*), 0)
    From  (
        Select 'green' As Color Union All
        Select 'blue' Union All
        Select 'red' Union All
        Select 'white' Union All
        Select 'black'
      ) c
        Left Outer Join
      ColorsFlavors cf
        On c.Color = cf.Color
    Group By
        c.Color
    

    有了这个,你应该可以弄出味道了!

    【讨论】:

    • 好吧,没有颜色表,但也许我可以通过连接“模拟”一个?
    • @JavierNovoaC。你说如果你有一个预定义的颜色列表可供选择。你从哪里弄来的?
    • @JavierNovoaC。我已经添加了更多选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 2018-09-09
    • 2017-11-13
    相关资源
    最近更新 更多