sqlpostgresqldbeaver

How can I write a SQL query to produce a count of each value seen in a particular column?


I have the following SQL query:

select * from sval where fid = 4052 and id in (select blah blah blah)));

And this produces:

    id      fid          timestamp           val  
403120126   4052    2019-02-01 00:00:00.000 FMUS
403120127   4052    2019-02-01 00:00:00.000 FMEE
403120136   4052    2019-02-01 00:00:00.000 FMUS
403120141   4052    2019-02-01 00:00:00.000 FMRU
403120170   4052    2019-02-01 00:00:00.000 FMUS
403120183   4052    2019-02-01 00:00:00.000 FMRU
403120188   4052    2019-02-01 00:00:00.000 FMEE
403120207   4052    2019-02-01 00:00:00.000 FMHK

I am trying to get a count of each value seen in the val column. Is this possible?

So for the above, I would ideally like to have:

val    count 
FMUS     3
FMEE     2
FMRU     2
FMHK     1

Solution

  • SELECT val
    ,Occurrences = COUNT(val)
    FROM sval
    WHERE ...
    GROUP BY val
    

    You just want to count the occurrences of each value, then a simple COUNT() and GROUP BY works.