40

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!

pkaeding
  • 36,513
  • 30
  • 103
  • 141

7 Answers7

77
SELECT A,B,COUNT(*)
FROM the-table
GROUP BY A,B
Lukasz Lysik
  • 10,462
  • 3
  • 51
  • 72
15

TRY:

SELECT
    A, B , COUNT(*)
    FROM YourTable
    GROUP BY A, B
KM.
  • 101,727
  • 34
  • 178
  • 212
10

This should do it:

SELECT A, B, COUNT(*) 
FROM TableName
GROUP BY A, B;
Moduo
  • 623
  • 6
  • 17
Ken White
  • 123,280
  • 14
  • 225
  • 444
7
SELECT A,B,COUNT(1) As COUNT_OF
FROM YourTable
GROUP BY A,B
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
6
SELECT A,B,COUNT(*)
FROM table
GROUP BY A,B
Moduo
  • 623
  • 6
  • 17
Radu094
  • 28,068
  • 16
  • 63
  • 80
5

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

pmarflee
  • 3,428
  • 20
  • 21
4

This could be the answer:

SELECT a, b, COUNT(*) 
FROM <your table name here> 
GROUP BY a,b 
ORDER BY 3 DESC;
Moduo
  • 623
  • 6
  • 17
snahor
  • 1,162
  • 1
  • 10
  • 16