返回表在每一列中列出了不同的值

时间:2018-12-26 18:10:58

标签: sql greenplum distinct-values

我熟悉一个数据表,该表有许多列,用于描述个人的工作角色。我想返回一个表,该表在每一列中列出表中每一列中存在的不同值。

我了解如何为单个列返回不同列表,但我希望将所有结果都放在一个表中,彼此相邻。顺序没关系。

示例性输入,其中每一行都是一名员工:

--title-- --function-- --class--
analyst    sleeping     professional
analyst    sleeping     ED
analyst    sleeping     MD
scientist  observing    VP
scientist  managing     VP
scientist  researching  associate

预期输出:

--title-- --function-- --class--
analyst   sleeping     professional
scientist observing    ED
          managing     MD
          researching  VP
                       associate

2 个答案:

答案 0 :(得分:1)

您可以使用这种方法。但是,这种操作与RDBMS系统的关系结构相矛盾。

select * from (
    select distinct title, null as function, null as class from Table1
    union
    select distinct null, function, null from Table1
    union 
    select distinct null, null, class from Table1
)
order by title, function, class

答案 1 :(得分:0)

您可以使用row_number()和聚合来完成此操作:

select min(title) as title, min(function) as function, min(class) as class
from ((select title, null as function, null as class,
              row_number() over (order by title) as seqnum
       from t
       group by title
      ) union all
      (select null as title, function, null as class,
              row_number() over (order by function) as seqnum
       from t
       group by function
      ) union all
      (select null as title, null as function, class,
              row_number() over (order by class) as seqnum
       from t
       group by class
      )
     ) tfc
group by seqnum;