[英]query that returns distinct count of each value in each column
I'm looking to query a table structured like so 我正在寻找查询结构像这样的表
A B C D E
1 1 1 1 1
2 2 1 1 2
2 2 2 1 3
4 4 5 5 5
to see the column_name, distinct_value_in_column, count_of_distinct_value like so 像这样查看column_name,distinct_value_in_column,count_of_distinct_value
A 1 1
A 2 2
A 4 2
B 1 1
B 2 2
B 4 1
C 1 2
C 2 1
C 5 1
D 1 3
D 5 1
E 1 1
E 2 1
E 3 1
E 5 1
Ultimately I'd like to sort by count descending, but it's getting to this structure that puzzles me. 最终,我想按降序排序,但是这种结构令我感到困惑。 Can this be done in SQL generally? 通常可以在SQL中完成吗? I'm using a postgresql instance if that has any impact. 我正在使用一个postgresql实例,如果有影响的话。
In pseudo code I'm envisioning 我在用伪代码设想
select column_names, distinct a, b, c, d, e, count (`distinct a, b, c, d, e) as ct
from table
group by column_names
order by ct desc
Sure. 当然。 Stack the data first using UNION
. 首先使用UNION
堆叠数据。
select
col,
val,
count(*)
from
(
select
'A' as col,
a as val
from
table
union all select
'B' as col,
b as val
from
table
union all select
'C' as col,
c as val
from
table
union all select
'D' as col,
d as val
from
table
union all select
'E' as col,
e as val
from
table
)
group by
col,
val
order by
count(*) desc;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.