MySQL:计算已知(或枚举)不同值的出现次数

时间:2014-05-27 15:10:54

标签: mysql sql

在字段中查看how to count the occurrences of distinct values之后,我想知道如果已知(或枚举)不同的值,如何计算每个不同值的出现次数。

例如,如果我有一个简单的表 -

TrafficLight        Colour
------------        ------
1                   Red 
2                   Amber
3                   Red 
4                   Red 
5                   Green 
6                   Green 

其中一列(在本例中为Color)具有已知(或枚举)的不同值,如何将每种颜色的计数作为单独的值返回,而不是像链接示例中那样作为数组返回。

要返回一个具有每种颜色计数的数组(使用与链接示例中相同的方法),查询将类似于SELECT Colour COUNT(*) AS ColourCount FROM TrafficLights GROUP BY Colour,并返回一个数组 -

Colour          ColourCount 
------          -----------
Red             3
Amber           1
Green           2

我想要做的是将每个Color AS的计数单独返回(例如RedCount)。我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:2)

对于mysql,你可以这样做,通过使用sum(expr)中的表达式将得到布尔值,你可以单独计算颜色的出现次数

SELECT 
SUM(Colour = 'Red') AS RedCount, 
SUM(Colour = 'Amber') AS AmberCount, 
SUM(Colour = 'Green') AS GreenCount
FROM t 

Demo

答案 1 :(得分:0)

尝试此查询:

SELECT
  (SELECT COUNT(*) AS ColourCount FROM tableA GROUP BY colour HAVING colour = 'Red') AS     red_lights,
  (SELECT COUNT(*) AS ColourCount FROM tableA GROUP BY colour HAVING colour = 'Green') AS green_lights,
  (SELECT COUNT(*) AS ColourCount FROM tableA GROUP BY colour HAVING colour = 'Amber') AS amber_lights
FROM
  tableA

Here is the Fiddle

答案 2 :(得分:-1)

您不必知道枚举值:

SELECT Colour, count(*) as Frequency FROM t GROUP BY Colour ;

如果您的代码被用于“琥珀色”被报告为“黄色”的地方,它仍然有效。