Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count rows that have the same values in two columns (SQL)?

Tags:

sql

I am sure there must be a relatively straightforward way to do this, but it is escaping me at the moment. Suppose I have a SQL table like this:

+-----+-----+-----+-----+-----+ |  A  |  B  |  C  |  D  |  E  | +=====+=====+=====+=====+=====+ |  1  |  2  |  3  | foo | bar | << 1,2 +-----+-----+-----+-----+-----+ |  1  |  3  |  3  | biz | bar | << 1,3 +-----+-----+-----+-----+-----+ |  1  |  2  |  4  |  x  |  y  | << 1,2 +-----+-----+-----+-----+-----+ |  1  |  2  |  5  | foo | bar | << 1,2 +-----+-----+-----+-----+-----+ |  4  |  2  |  3  | foo | bar | << 4,2 +-----+-----+-----+-----+-----+ |  1  |  3  |  3  | foo | bar | << 1,3 +-----+-----+-----+-----+-----+ 

Now, I want to know how many times each combination of values for columns A and B appear, regardless of the other columns. So, in this example, I want an output something like this:

+-----+-----+-----+ |  A  |  B  |count| +=====+=====+=====+ |  1  |  2  |  3  | +-----+-----+-----+ |  1  |  3  |  2  | +-----+-----+-----+ |  4  |  2  |  1  | +-----+-----+-----+ 

What would be the SQL to determine that? I feel like this must not be a very uncommon thing to want to do.

Thanks!

like image 645
pkaeding Avatar asked Oct 20 '09 20:10

pkaeding


People also ask

How do I count matching rows in SQL?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.

Can we use count on multiple columns in SQL?

You can use CASE statement to count two different columns in a single query. To understand the concept, let us first create a table. The query to create a table is as follows. Insert some records in the table using insert command.


2 Answers

SELECT A,B,COUNT(*) FROM the-table GROUP BY A,B 
like image 174
Lukasz Lysik Avatar answered Oct 15 '22 05:10

Lukasz Lysik


TRY:

SELECT     A, B , COUNT(*)     FROM YourTable     GROUP BY A, B 
like image 22
KM. Avatar answered Oct 15 '22 04:10

KM.