同一表的不同列的计数总和
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了同一表的不同列的计数总和相关的知识,希望对你有一定的参考价值。
下面给出了表格
+---+---+
| 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
答案
尝试:
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;
另一答案
您可以使用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
另一答案
声明@table table(x int,y int)insert into @table select 1,2 union all select 1,5 union all select 5,2 union all select 5,1 select x,SUM(a)from(select x,COUNT ()作为来自@table组的x union所有选择y,COUNT()作为来自@table组的y)a by x by x
另一答案
可能最简单的方法是选择所有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;
以上是关于同一表的不同列的计数总和的主要内容,如果未能解决你的问题,请参考以下文章