Count the occurrences across multiple columns

江枫思渺然 提交于 2020-01-05 02:34:57

问题


Im trying to count occurrences across multiple columns in a table. All values are integers and all the numbers are unique in each row. (i.e you won't get two values occurring in the same row) The table structure is:

ID  Number1  Number2  Number3  Number4  Number5  Number6
---------------------------------------------------------
    11       6        4        5        9        8
    6        9        11       5        3        15
    8        5        9        11       4        6
    4        11       17       3        7        1

The expected output would be something like:

Number  Count
--------------
11      4
6       3
4       3
5       3
9       3
3       2
8       2
15      1
17      1
7       1
1       1

I've tried using pivots and various other methods found on the internet but just can't seem to get it working correctly. Any ideas, it seems like a simple query but I just can't get it right.


回答1:


If there are only 6 columns, then one way you can do this

select Number, count(*) From (select Number1 as Number from your_table
union all
select Number2 as Number from your_table
union all
select Number3 as Number from your_table
union all
select Number4  as Number from your_table
union all
select Number5  as Number from your_table
union all
select Number6 as Number from your_table) myTab
group by Number;


来源:https://stackoverflow.com/questions/31227563/count-the-occurrences-across-multiple-columns

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