This is a s开发者_JS百科implified 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
精彩评论