42

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!

7 Answers 7

78
SELECT A,B,COUNT(*)
FROM the-table
GROUP BY A,B
Sign up to request clarification or add additional context in comments.

Comments

15

TRY:

SELECT
    A, B , COUNT(*)
    FROM YourTable
    GROUP BY A, B

Comments

11

This should do it:

SELECT A, B, COUNT(*) 
FROM TableName
GROUP BY A, B;

Comments

7
SELECT A,B,COUNT(1) As COUNT_OF
FROM YourTable
GROUP BY A,B

Comments

6
SELECT A,B,COUNT(*)
FROM table
GROUP BY A,B

Comments

5

SELECT A, B, COUNT(*) FROM MyTable GROUP BY A, B

Comments

5

This could be the answer:

SELECT a, b, COUNT(*) 
FROM <your table name here> 
GROUP BY a,b 
ORDER BY 3 DESC;

4 Comments

Also correct, but ordering by ordinals isn't a good habit iirc.
I thought I'd be the first to answer T_T.
@rexem I suppose you say it because of readability, I can't find other reason.
@snahor: It's because the ordinal is associated with the position in the SELECT. If it moves, your ordering changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.