user3663882
user3663882

Reputation: 7367

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

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)

Upvotes: 9

Views: 60811

Answers (2)

OVY78
OVY78

Reputation: 1

For me works only something like this:

SELECT player_id
FROM table_name
WHERE player_id = 1 ( "and" another condition when needed)
SELECT @@ROWCOUNT

Upvotes: -1

Elliot B.
Elliot B.

Reputation: 17681

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;

Upvotes: 34

Related Questions