SQL 如何计算数据库列中所有不同值的出现次数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2866764/
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
How to count number of occurrences for all different values in database column?
提问by Rasto
I have a Postgre database that has say 10 columns. The fifth column is called column5
. There are 100 rows in the database and possible values of column5
are c5value1, c5value2, c5value3...c5value29, c5value30
. I would like to print out a table that shows how many times each value occurs.
我有一个有 10 列的 Postgre 数据库。第五列称为column5
。有100行的数据库和可能的值column5
ARE c5value1, c5value2, c5value3...c5value29, c5value30
。我想打印一个表格,显示每个值出现的次数。
So the table would look like this:
所以表格看起来像这样:
Value(of column5) number of occurrences of the value
c5value1 1
c5value2 5
c5value3 3
c5value4 9
c5value5 1
c5value6 1
. .
. .
. .
What is the command that does that?
执行此操作的命令是什么?
回答by Mark Byers
Group by the column you are interested in and then use count to get the number of rows in each group:
按您感兴趣的列分组,然后使用 count 获取每组中的行数:
SELECT column5, COUNT(*)
FROM table1
GROUP BY column5