1

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

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 查询是什么?

4

1 回答 1

4

完成 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

有了这个,你应该能够解决口味!

于 2012-11-17T01:07:44.843 回答