【问题标题】:Select independent distinct with one query一次查询选择独立不同
【发布时间】:2013-03-19 20:51:48
【问题描述】:

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

其中“-”是一个空条目。

【问题讨论】:

  • 请通过添加适当的标签(Oracle、SQL Server、MySQL 等)指定您的目标关系数据库管理系统。可能有一些答案利用了不受普遍支持的语言或产品功能。此外,通过使用特定的 RDBMS 对其进行标记,您的问题可能会受到更适合回答的人的关注
  • 通用对任何人都没有帮助,因为即使是“标准”语法也可能因平台而异,更不用说最有效的路径可能会利用特定于平台的扩展。
  • 明白了,我想我会针对 h2 调整问题。
  • 标签已经涵盖了您的问题是关于 H2 的事实,you don't need to put the name in the title

标签: sql distinct h2 multiple-columns


【解决方案1】:

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

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() 函数(记录在 here 中)。但是,您可能无法指定顺序。

【讨论】:

  • 看来h2不支持over子句,请问有替代方法吗?
  • 它可以工作,但它比单独运行 select 语句 (0+0+0 = 0ms) 需要更长的时间 (31 ms)。谢谢你的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 1970-01-01
  • 2017-02-19
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多