简体   繁体   中英

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. Data is accessed using 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.

Please, pay attention, that rows with flag = 1 and rows with flag = 0 have opposite sort order.

Is it possible to do in SQL? I wouldn`t like to make two queries and merge ResultSets in Java code manually.

In any SQL, only the outermost order by applies so it has to be done there.

I don't know if this works in your SQL dialect (and can't check sorry), but you could do this

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. Think "SQL first".

order by can take more than one column:

select *
from table
order by flag desc, name asc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM