同一表的不同列的计数总和

时间:2017-12-18 21:44:14

标签: sql count sum multiple-columns

下面给出了一个名为table

的表
+---+---+
| x | y |
+---+---+
| 1 | 2 |
| 1 | 5 |
| 5 | 2 |
| 5 | 1 |
+---+---+

我想对以下结果进行SQL查询

+----+-------------+
| id | count_total |
+----+-------------+
|  1 |           3 |
|  2 |           2 |
|  5 |           3 |
+----+-------------+

注意: 我能够分别计算每个id的行数,但是我无法得到相同id的总和。 所以我想在一个查询中组合或得到以下查询的总和。

SELECT x, count(*) as total_x FROM table GROUP BY x
SELECT y, count(*) as total_y FROM table GROUP BY y

4 个答案:

答案 0 :(得分:1)

尝试:

SELECT
A.ID, SUM(A.COUNTS) AS COUNT_TOTAL
FROM
(
SELECT X AS ID, COUNT(*) AS COUNTS FROM TABLE1 GROUP BY X
UNION ALL
SELECT Y AS ID, COUNT(*) AS COUNTS FROM TABLE1 GROUP BY Y
) A
GROUP BY A.ID
ORDER BY A.ID;

答案 1 :(得分:0)

您可以使用union将它们组合在一起,我实际上没有尝试过,但它应该可以正常工作。如果它不起作用请发表评论,我很乐意帮助和编辑我的答案。

select u.x, sum(u.total) 
from 
(
(SELECT x as x, count(*) as total FROM table GROUP BY x) 
union all 
(SELECT y as x, count(*) as total FROM table GROUP BY y)  
) as u 
group by u.x

答案 2 :(得分:0)

声明@table表 ( x int, y int ) 插入@table 选择1,2 union all 选择1,5 union all 选择5,2 union all 选择5,1 选择x,SUM(a)from( 选择x,COUNT()作为来自@table组的x 联合所有 选择y,COUNT()作为来自@table组的y ) 一个 分组x

答案 3 :(得分:0)

可能最简单的方法是选择所有x和所有y然后聚合它们。

select id, count(*) as count_total 
from (select x as id from mytable union all select y from mytable) ids
group by id
order by id;