Search code examples
sql-order-byhql

HQL custom order ASC and DESC


I have the following situation:

I have a bill with a year (e.g. 2000, 2001, ...), a boolean that says whether the bill was paid or not and different other values like a persons name.

It comes that I want to display them in a list in a specific order. The oldest unpaid bill should be on top and the oldest paid bill should be at the bottom. Also it should be sorted by the name. Like:

Name   Year  PAID
Smith  2010  false
Otto   2018  false
Anon   2018  true
Hueue  2018  true
Otto   2017  true
Smith  2009  true

Something like that...

"from Bill as b order by b.paid, b.year, b.name"

This clause sorts the list like:

Name   Year  PAID
Smith  2010  false
Otto   2018  false
Smith  2009  true
Otto   2017  true
Anon   2018  true
Hueue  2018  true

I tried to achieve my goal with HQL (order by case...) but I don't know how to order the same row in different ways depending on a value. Like: (this does not work)

" from Bill as b" +
" order by" +
" b.paid," +
" (case b.year" +
"   WHEN b.paid" +
"   THEN b.year" +
"   ELSE -b.year" +
" end)," +
" b.name"

Thanks for your help in advance.

Edit: Added more explanation and examples...


Solution

  • Try this query:

    from Bill as b
    order by
        b.paid,
        case when b.paid = 'false' then b.year else -b.year end,
        b.name
    

    This works by first placing unpaid bill records before paid records. For this first sort condition we need not use a case expression because false sorts before true. For the year order, we do need a case expression. Here we sort ascending by year for unpaid bills and descending for paid bills.