sum of counts of different columns of same table

本小妞迷上赌 提交于 2019-12-10 11:54:27

问题


Given below table called table

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

I want to have sql query for the following results

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

Note: I was able to count separately the rows per id but I could not get the sum for the same id. so I want to combine or get sum of below queries in a single query.

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

回答1:


Try:

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;



回答2:


You can use union to bring them together, I did not try it actually but it should work fine. if it did not work please leave a comment and I would be happy to help and edit my answer.

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



回答3:


declare @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() as a from @table group by x union all select y,COUNT() as a from @table group by y ) a group by x




回答4:


Probably the easiest way is to select all x and all y and then aggregate over them.

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;


来源:https://stackoverflow.com/questions/47876861/sum-of-counts-of-different-columns-of-same-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!