简体   繁体   English

SQL 查询 - 将 count() 结果拆分为一行 GROUP BY 结果

[英]SQL query - split out count() results into one line of GROUP BY results

I want to use GROUP BY to get a row per month-year.我想使用 GROUP BY 来获取每个月/年的一行。 Additionally, I have another field which, for this example, is colour and can have values of Blue or Red.此外,我还有另一个字段,在这个例子中,它是颜色,可以有蓝色或红色的值。

I want to see a table with columns for Blue, Red, month and year = I want to count the number of each colour per month-year.我想查看一个包含蓝色、红色、月份和年份列的表格 = 我想计算每个月-年每种颜色的数量。 Can I do this with an SQL query?我可以使用 SQL 查询来执行此操作吗?

I know that count(colour) will give me the total number of rows for each month-year.我知道 count(color) 会给我每个月每年的总行数。

It's good if it's possible to do this but some solutions may involve coding in "Red" and "Blue" = just 2 values.如果可以做到这一点很好,但某些解决方案可能涉及“红色”和“蓝色”编码 = 仅 2 个值。 Is it possible to run a query to execute a count which will split out the "answers" from the count into each line rather than a line each?是否可以运行查询来执行计数,将计数中的“答案”分成每一行而不是每行?

Example data:示例数据:

Year Month Day Colour颜色
2021 2021 3 3 6 6 Blue蓝色的
2021 2021 3 3 7 7 Blue蓝色的
2021 2021 3 3 8 8 Blue蓝色的
2021 2021 3 3 9 9 Red红色的
2021 2021 4 4 5 5 Blue蓝色的
2021 2021 4 4 6 6 Red红色的
2021 2021 4 4 7 7 Blue蓝色的
2021 2021 4 4 8 8 Red红色的
2021 2021 4 4 9 9 Red红色的

to give result给出结果

Year Month Blue蓝色的 Red红色的
2021 2021 3 3 3 3 1 1
2021 2021 4 4 2 2 3 3

I'm doing this in mysql and also in javascript using alasql but a suggestion for any version of SQL will probably be helpful here...我在 mysql 和 javascript 中使用 alasql 执行此操作,但对任何版本的 SQL 的建议可能在这里会有所帮助...

You can use SUM(CASE WHEN... to do this您可以使用SUM(CASE WHEN...来执行此操作

SELECT Year, Month, SUM(CASE WHEN Colour = 'Blue' THEN 1 ELSE 0 END) AS Blue, etc
FROM table
GROUP BY Year, Month

I will suggest fixing the design.我会建议修复设计。 You could store date in one column only, in date format.您只能以日期格式将日期存储在一列中。 Be aware of the MySQL reserved word such as YEAR , MONTH , DATE , you should use backticks for those columns.请注意MySQL 保留字,例如YEARMONTHDATE ,您应该为这些列使用反引号。

If you only have blue and red color you could do an easy solution:如果你只有蓝色和红色,你可以做一个简单的解决方案:

SELECT Year, 
       Month, 
       SUM(Colour='Blue') as Blue, 
       SUM(Colour='Red') as Red   
FROM test_tbl    
GROUP BY `Year`, `Month`;

Result:结果:

 Year Month Blue Red 2021 3 3 1 2021 4 2 3

Demo 演示

You could do the following:您可以执行以下操作:

  GROUP BY Year(yourdate),
     Month(yourdate),
     Day(yourdate),
     Colour

Group By is not limited to acting on a single column (or expression). Group By 不限于作用于单个列(或表达式)。

You can write a query like this您可以编写这样的查询

SELECT Year, 
       Month, 
       COUNT(CASE WHEN Colour = 'Blue' THEN 1 END) AS Blue, 
       COUNT(CASE WHEN Colour = 'Red' THEN 1 END) AS Red    
FROM table    
GROUP BY Year, Month;

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

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