我的这张表有一些数据:
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查询会是什么?
答案 0 :(得分: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
有了这个,你应该能够计算出口味!