[英]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.