在一个查询中选择独立的



我需要从h2数据库中的多个列中选择不同的值,这样我就可以根据数据库中的内容为用户提供建议列表。换句话说,我需要像

这样的东西
SELECT DISTINCT a FROM table
SELECT DISTINCT b FROM table
SELECT DISTINCT c FROM table

在一个查询中。如果我不够清楚,我想要一个查询给定这个表(列ID, thing, other, stuff)

0 a 5 p
1 b 5 p
2 a 6 p
3 c 5 p

会导致如下的结果

a 5 p
b 6 -
c - -

其中'-'为空条目

这有点复杂,但是您可以这样做:

select max(thing) as thing, max(other) as other, max(stuff) as stuff
from ((select row_number() over (order by id) as seqnum, thing, NULL as other, NULL as stuff
       from (select thing, min(id) as id from t group by thing
            ) t
      ) union all
      (select row_number() over (order by id) as seqnum, NULL, other, NULL
       from (select other, min(id) as id from t group by other
            ) t
      ) union all
      (select row_number() over (order by id) as seqnum, NULL, NULL, stuff
       from (select stuff, min(id) as id from t group by stuff
            ) t
      )
     ) t
group by seqnum

的作用是为每列中的每个不同的值分配一个序列号。然后,它将这些组合成一个单行的每个序列号。该组合采用union all/group by方法。另一种配方使用full outer join

这个版本使用id列来保持值在原始数据中出现的顺序相同。

在H2(这不是最初的问题),您可以使用rownum()函数代替(文档在这里)。但是,您可能无法指定排序。

最新更新