Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

How to count rows that have the same values in two columns (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!

question from:https://stackoverflow.com/questions/1597055/how-to-count-rows-that-have-the-same-values-in-two-columns-sql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
SELECT A,B,COUNT(*)
FROM the-table
GROUP BY A,B

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...