SQL 是否可以使用 COUNT 计算具有相同 ID 的所有行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30932283/
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
Is it possible to count all rows with the same id with COUNT?
提问by user3663882
PostgreSQL 9.4
.
PostgreSQL 9.4
.
I have the following table:
我有下表:
id player_id
serial PK integer
---------------------------
1 1
2 3
... ...
123123 1
I need to count all rows with player_id = 1
. Is it possible to do with the COUNT
aggregate?
我需要用player_id = 1
. 可以用COUNT
聚合吗?
Now I do it as follows:
现在我这样做:
SUM(CASE WHEN player_id = 1 THEN 1 ELSE 0 END)
回答by Elliot B.
If all you need is a count of the number of rows where player_id
is 1, then you can do this:
如果您只需要计算行数player_id
为 1,那么您可以执行以下操作:
SELECT count(*)
FROM your_table_name
WHERE player_id = 1;
If you want to count the number of rows for eachplayer_id
, then you will need to use a GROUP BY
:
如果要计算每个的行数player_id
,则需要使用GROUP BY
:
SELECT player_id, count(*)
FROM your_table_name
GROUP BY player_id;