如何计算在两列(SQL)中具有相同值的行?

时间:2022-02-20 14:01:52

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:

我确信一定有一种相对简单的方法可以做到这一点,但目前我还没有意识到这一点。假设我有一个这样的SQL表:

+-----+-----+-----+-----+-----+
|  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的每个值组合出现的次数。所以,在这个例子中,我想要输出如下内容:

+-----+-----+-----+
|  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.

什么是SQL来确定?我觉得这肯定不是一件很少见的事情。

Thanks!

谢谢!

7 个解决方案

#1


60  

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

#2


14  

TRY:

试一试:

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

#3


9  

This should do it:

这应该这样做:

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

#4


6  

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

#5


5  

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

#6


4  

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

从MyTable组中选择A、B、COUNT(*)

#7


2  

This could be the answer:

这可能就是答案:

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

#1


60  

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

#2


14  

TRY:

试一试:

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

#3


9  

This should do it:

这应该这样做:

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

#4


6  

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

#5


5  

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

#6


4  

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

从MyTable组中选择A、B、COUNT(*)

#7


2  

This could be the answer:

这可能就是答案:

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