查询返回每列中每个值的不同计数

时间:2016-03-15 18:14:17

标签: sql postgresql

我正在寻找一个像这样结构的表

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

查看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

归根结底,我想按计数降序排序,但这种结构让我感到困惑。这可以在SQL中完成吗?如果有任何影响,我正在使用postgresql实例。

在伪代码中,我正在设想

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

2 个答案:

答案 0 :(得分:0)

不确定。首先使用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;

答案 1 :(得分:0)

您可以使用以下查询:

SELECT col, val, count(*)
FROM (
  SELECT unnest(array['A','B','C','D','E']) AS col,
         unnest(array[A,B,C,D,E]) AS val
  FROM mytable) AS t
GROUP BY col, val

Demo here