我需要从 h2 中的多个列中选择不同的值数据库,这样我就可以根据数据库中的内容为用户提供建议列表。换句话说,我需要类似的东西
SELECT DISTINCT a FROM table
SELECT DISTINCT b FROM table
SELECT DISTINCT c FROM table
在一个查询中。如果我不够清楚,我想要一个给出该表的查询(列 ID、事物、其他、事物)
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
方法。另一种公式使用完全外连接
。
此版本使用 id
列来保持值的顺序与原始数据中显示的顺序相同。
在 H2 中(最初不是这个问题),您可以使用 rownum()
函数(记录为 here )。但是,您可能无法指定顺序。
关于sql - 通过一个查询选择独立的不同项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15510194/