开发者

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

开发者 https://www.devze.com 2022-12-08 20:14 出处:网络
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:

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 开发者_如何学Go |  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!


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


TRY:

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


This should do it:

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


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


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


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


This could be the answer:

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

精彩评论

暂无评论...
验证码 换一张
取 消