计算跨多个列的事件。

时间:2021-06-11 15:42:01

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:

我尝试在一个表的多个列中计算出现的次数。所有的值都是整数,每一行中的所有数字都是唯一的。(我。e你不会在同一行中出现两个值)表结构是:

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 个解决方案

#1


2  

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

如果只有6列,那么有一种方法

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;

#1


2  

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

如果只有6列,那么有一种方法

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;