如何计算两列(SQL)中具有相同值的行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1597055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count rows that have the same values in two columns (SQL)?
提问by pkaeding
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!
谢谢!
回答by Lukasz Lysik
SELECT A,B,COUNT(*)
FROM the-table
GROUP BY A,B
回答by KM.
TRY:
尝试:
SELECT
A, B , COUNT(*)
FROM YourTable
GROUP BY A, B
回答by Ken White
This should do it:
这应该这样做:
SELECT A, B, COUNT(*)
FROM TableName
GROUP BY A, B;
回答by Adriaan Stander
SELECT A,B,COUNT(1) As COUNT_OF
FROM YourTable
GROUP BY A,B
回答by Radu094
SELECT A,B,COUNT(*)
FROM table
GROUP BY A,B
回答by pmarflee
SELECT A, B, COUNT(*) FROM MyTable GROUP BY A, B
SELECT A, B, COUNT(*) FROM MyTable GROUP BY A, B
回答by snahor
This could be the answer:
这可能是答案:
SELECT a, b, COUNT(*)
FROM <your table name here>
GROUP BY a,b
ORDER BY 3 DESC;