问题
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