简体   繁体   English

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

[英]MySQL: Count occurrences of known (or enumerated) distinct values

After looking at how to count the occurrences of distinct values in a field, I am wondering how to count the occurrences of each distinct value if the distinct values are known (or enumerated). 在查看如何计算字段中不同值的出现次数之后 ,我想知道如果已知(或枚举)不同的值,如何计算每个不同值的出现次数。

For example, if I have a simple table - 例如,如果我有一个简单的表 -

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

where one column (in this case Colour) has known (or enumerated) distinct values, how could I return the count for each colour as a separate value, rather than as an array, as in the linked example. 其中一列(在本例中为Color)已知(或枚举)不同的值,我如何将每种颜色的计数作为单独的值返回,而不是像链接的示例中那样作为数组返回。

To return an array with a count of each colour (using the same method as in the linked example), the query would be something like SELECT Colour COUNT(*) AS ColourCount FROM TrafficLights GROUP BY Colour , and return an array - 要返回一个具有每种颜色计数的数组(使用与链接示例中相同的方法),查询将类似于SELECT Colour COUNT(*) AS ColourCount FROM TrafficLights GROUP BY Colour ,并返回一个数组 -

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

What I would like to do is to return the count for each Colour AS a separate total (eg RedCount). 我想要做的是将每个Color AS的计数单独返回(例如RedCount)。 How can I do this? 我怎样才能做到这一点?

For mysql you can do so,by using expression in sum(expr) will result as boolean and you can count the occurrences for your colors individually 对于mysql,你可以这样做,通过在sum(expr)使用表达式将得到布尔值,你可以单独计算颜色的出现次数

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

Demo 演示

Try this query: 试试这个查询:

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 这是小提琴

You don't have to know the enumerated values: 您不必知道枚举值:

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

If your code gets used where 'amber' is reported as 'yellow', it still works. 如果您的代码被用于“琥珀色”被报告为“黄色”的地方,它仍然有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM