Rasvet Rasvet - 1 year ago 36
SQL Question

How to calculate count of records by 2 columns


I have a table.


id name type
1 Thomas 2
2 Thomas 2
3 Thomas 1
4 Paul 3
5 Paul 4
6 Paul 4

I need calculate same records by 2 columns.
Result for this example should be:

name type countOfRecords
Thomas 2 2
Thomas 1 1
Paul 3 1
Paul 4 2

Could you help me with this request?

Answer Source

Since you want records in your result set for each name and type <name,type> pair you need to group by name and type.

COUNT(*) countOfRecords
FROM your_table
GROUP BY name,type;


Group BY <some column> would generate a result set where number of rows = number of distinct / different / unique <some column>.

Same holds for multiple columns in GROUP BY clause.