Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to count all rows with the same id with COUNT?

Tags:

sql

postgresql

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?

Now I do it as follows:

SUM(CASE WHEN player_id = 1 THEN 1 ELSE 0 END)
like image 657
user3663882 Avatar asked Jun 19 '15 07:06

user3663882


1 Answers

If all you need is a count of the number of rows where player_id is 1, then you can do this:

SELECT count(*)
FROM your_table_name
WHERE player_id = 1;

If you want to count the number of rows for each player_id, then you will need to use a GROUP BY:

SELECT player_id, count(*)
FROM your_table_name
GROUP BY player_id;
like image 197
Elliot B. Avatar answered Oct 13 '22 00:10

Elliot B.