sql - 通过一个查询选择独立的不同项

标签 sql distinct h2 multiple-columns

我需要从 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/

相关文章:

c# - 以文本形式返回数字

sql - sql 中的 max 没有从数据库中得到正确的结果(使用 laravel 框架)

c# - 使用 NHibernate 获取不同的 IQueryable

java - H2 的 Hibernate Multi-Tenancy 问题 : wrong schema

java - 如何将完整的 H2 源代码包含到 Java 项目中?

sql - 使用窗口函数动态选择任意 n 列

MySql 按结果分组的计数

postgresql - 从 Postgresql 表中选择不同的数组值

mysql - 如何在 SQL 中选择具有 MAX(列值)、DISTINCT by MULTIPLE 列的行

java - 如何解决 H2 "Error executing DDL"错误?