我确信必须有一种相对简单的方法来做到这一点,但它现在正在逃避我。假设我有一个这样的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
+-----+-----+-----+-----+-----+
现在,我想知道列A和B的每个值组合出现多少次,而不管其他列。所以,在这个例子中,我想要一个像这样的输出:
+-----+-----+-----+
| A | B |count|
+=====+=====+=====+
| 1 | 2 | 3 |
+-----+-----+-----+
| 1 | 3 | 2 |
+-----+-----+-----+
| 4 | 2 | 1 |
+-----+-----+-----+
确定这个的SQL是什么?我觉得这绝不是一件非常不寻常的事情。
谢谢!
答案 0 :(得分:65)
SELECT A,B,COUNT(*)
FROM the-table
GROUP BY A,B
答案 1 :(得分:14)
TRY:
SELECT
A, B , COUNT(*)
FROM YourTable
GROUP BY A, B
答案 2 :(得分:9)
这应该这样做:
SELECT A, B, COUNT(*)
FROM TableName
GROUP BY A, B;
答案 3 :(得分:6)
SELECT A,B,COUNT(1) As COUNT_OF
FROM YourTable
GROUP BY A,B
答案 4 :(得分:5)
SELECT A,B,COUNT(*)
FROM table
GROUP BY A,B
答案 5 :(得分:4)
SELECT A,B,COUNT(*) 来自MyTable GROUP BY A,B
答案 6 :(得分:3)
这可能就是答案:
SELECT a, b, COUNT(*)
FROM <your table name here>
GROUP BY a,b
ORDER BY 3 DESC;