SQL SQL查找列中每种类型的总数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32595456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:03:13  来源:igfitidea点击:

SQL find total count of each type in a column

sql

提问by Wes Doyle

I'm learning SQL and am stumped on what should be a simple query. I have a table with the following pattern:

我正在学习 SQL 并且对什么应该是一个简单的查询感到困惑。我有一个具有以下模式的表:

Id |  Type  
------------
1  |  Red   
2  |  Blue  
3  |  Blue  
4  |  Red   
..

I would like to write a query to return a table that counts the total number of instances of each type and returns a table with the following pattern, for example, if 'Blue' occurs in 12 rows, and 'Red' occurs in 16 rows in the table above, the result would be:

我想编写一个查询来返回一个表,该表计算每种类型的实例总数并返回一个具有以下模式的表,例如,如果 'Blue' 出现在 12 行中,而 'Red' 出现在 16 行中在上表中,结果将是:

Blue | Red 
-----------
 12  |  16 

回答by Will

You could do it this way:

你可以这样做:

SELECT Type, COUNT(*) FROM TABLE GROUP BY Type

If you'd like to see the Types in separate columns, you could do this:

如果您想在单独的列中查看类型,您可以这样做:

SELECT SUM(CASE WHEN Type = 'Blue' THEN 1 ELSE 0 END) AS Blue, SUM(CASE WHEN Type = 'Red' THEN 1 ELSE 0 END) AS Red FROM TABLE