views:

200

answers:

3

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.

+2  A: 

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".

duffymo
Please, pay attention, that column name in rows where flag = 0 has opposite sort order.
Ilya
Please write a coherent question and stop being rude. I'm down voting your question now.
duffymo
@Ilya: you added this requirement after this answer
gbn
@gbn - not exactly, the requirement was there before, he just edited it to make it clearer when he saw that people were misunderstanding
froadie
@duffymo: That condition was from the very beginning. After I saw that people were misunderstanding, I made key words bold and added phrase "Please, pay attention..." to make question clearer.@froadie: Thanks. Everything was exactly as you described.
Ilya
+1  A: 

order by can take more than one column:

select *
from table
order by flag desc, name asc
meriton
+3  A: 

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
gbn
Thanks, your solution works in HSQLDB.But could you please explain how does sorting work in database? Engine selects rows and then applies two kinds of order expressions either this: "flag desc, name, '' desc" (if flag = 1) or this: "flag desc, '', name desc" (if flag = 0)? I have never met dynamic "order by" expression before.
Ilya
It sorts on 3 columns, but either column 2 or column 3 is a constant so is effectively ignored
gbn