Skip to content
Advertisement

GROUP on one column and aggregate counts based on distinct values in another column

I have a table with values like so:

I want to do a GROUP BY based on ts and display the counts for distinct values of usr_id like below.

ts count of A count of B count of others
11 2 1 3
22 0 1 0
33 1 0 3

http://www.sqlfiddle.com/#!9/bbf4fc/2

I couldn’t make much progress beyond doing the GROUP BY for ts: select ts, usr_id, count(*) from myTable group by ts, usr_id; But I want the counts of rows with A, B and others in the same row, can’t figure out how to achieve that.

Advertisement

Answer

This is your query

Demo

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement