tags:

views:

214

answers:

8

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!

+10  A: 
SELECT A,B,COUNT(*)
FROM the-table
GROUP BY A,B
Lukasz Lysik
+5  A: 

TRY:

SELECT
    A, B , COUNT(*)
    FROM YourTable
    GROUP BY A, B
KM
+4  A: 

This should do it:

SELECT A, B, COUNT(*) FROM YourTable
GROUP BY A, B
Ken White
+3  A: 

select A,B, count (*) from table group by A,B

Radu094
+3  A: 

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

pmarflee
+4  A: 
SELECT A,B,COUNT(1) As COUNT_OF
FROM YourTable
GROUP BY A,B
astander
+1  A: 

I agree with Lukasz Lysik, KM, pmarflee, astander, Ken White and Radu094 answers.

Rodrigo
yes, there definitely seems to be a consensus!
pkaeding
I didn't mark you down, but this is better served as a comment on the question.
OMG Ponies
know your meme!
Rodrigo
A: 

This could be the answer:

select a, b, count(*) 
from <your table name here> 
group by a,b 
order by 3 desc;
snahor
Also correct, but ordering by ordinals isn't a good habit iirc.
OMG Ponies
I thought I'd be the first to answer T_T.
snahor
@rexem I suppose you say it because of readability, I can't find other reason.
snahor
@snahor: It's because the ordinal is associated with the position in the SELECT. If it moves, your ordering changes.
OMG Ponies