简体   繁体   English

如何从一个使用SQL查询独立排序的表中合并两个结果集?

[英]How to combine two result sets from one table sorted independently using one SQL query?

This is a simplified task which I have to solve in real project. 这是我必须在实际项目中解决的简化任务。 In this project data is stored in HSQLDB. 在此项目中,数据存储在HSQLDB中。 Data is accessed using JDBC. 使用JDBC访问数据。

I have one table: 我有一张桌子:

name | flag
-----------
aa   | 1
bb   | 0
cc   | 1
dd   | 0
ee   | 1
ff   | 0

I need to compose query to get the following table: 我需要撰写查询以获取下表:

name | flag
-----------
aa   | 1
cc   | 1
ee   | 1
ff   | 0
dd   | 0
bb   | 0

The final table is like rows with flag = 1 were taken and sorted ascending , rows with flag = 0 were taken and sorted descending and results were combined one after another. 最终表就像采用flag = 1的行并升序排序,采用flag = 0的行并降序排序,结果依次合并。

Please, pay attention, that rows with flag = 1 and rows with flag = 0 have opposite sort order. 请注意,标志= 1的行和标志= 0的行具有相反的排序顺序。

Is it possible to do in SQL? 可以在SQL中执行吗? I wouldn`t like to make two queries and merge ResultSets in Java code manually. 我不想进行两个查询并以Java代码手动合并ResultSet。

In any SQL, only the outermost order by applies so it has to be done there. 在任何SQL中,仅应用最外面的顺序,因此必须在此完成。

I don't know if this works in your SQL dialect (and can't check sorry), but you could do this 我不知道这是否可以在您的SQL方言中使用(并且无法检查对不起),但是您可以这样做

SELECT name, flag
FROM  'table'
ORDER BY
    flag desc,
    CASE WHEN flag = 1 THEN name ELSE '' END,
    CASE WHEN flag = 0 THEN name ELSE '' END DESC

Try this: 尝试这个:

SELECT name, flag
FROM 'table'
ORDER BY flag desc, name

Let the database do the work whenever you can. 让数据库尽一切可能进行工作。 Don't do such things in Java. 不要在Java中执行此类操作。 Think "SQL first". 认为“ SQL首先”。

order by can take more than one column: order by可以占用多个列:

select *
from table
order by flag desc, name asc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将Sparql查询的两个不同但相关的结果集组合为一个? - How to combine two different but correlated result sets of a Sparql query into one? 如何结合两个ListenableFutures并从第一个中获得结果以完成 - How combine two ListenableFutures and get the result from the first one to complete 在Hibernate中将两个SQL查询调用合并为一个 - Combine two SQL query calls into one in Hibernate 如何使用Java使两个GUI滑块彼此独立工作? - How can I make two GUI sliders work independently from one another using Java? 如何将两个 FOR 合二为一 - How to combine two FORs into one 使用参数中第一个的结果将两个Observable与第二个 - Combine two Observables with the second using results from the first one in parameters 一个连接表中有多个@ManyToMany集 - Multiple @ManyToMany sets from one join table 如何使用带有联接的查询从jOOQ中仅选择一个表? - How to select from only one table in jOOQ using a query with a join? 如何使用一个 sql 查询从多个表中删除一行,其中 email id 相同 - How to Delete a row from more than one table with one sql query where email id is same 使用 MyBatis。 如何在一个表中 map 两个不同的记录,然后在加入该表时构造一个查询结果? - With MyBatis. How can I map two different records in one table, then construct a single query result when joining that table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM