Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting occurrences of a value in a column of a table - postgresql

Tags:

postgresql

I have a table with multiple columns:

table1 | column1 | column2 | column3 |
       |    x    |  ....   |   ....  |
       |    y    |  ....   |   ....  |
       |    x    |  ....   |   ....  |

How can I count the occurences of a value, for example x, in one of the columns, for example column1? Given table1 this would have to return me 2 (numbers of x present in column1).

like image 514
Victor Turrisi Avatar asked Dec 08 '22 01:12

Victor Turrisi


2 Answers

You can use SUM() aggregate function with a CASE statement like

select sum(case when column1 = 'x' then 1 else 0 end) as X_Count
from tabl1;
like image 77
Rahul Avatar answered Dec 11 '22 12:12

Rahul


SELECT COUNT(*) FROM table1 WHERE column1 = 'x'
like image 43
eugenioy Avatar answered Dec 11 '22 11:12

eugenioy