1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[SQL] ORDER BY column, with specific notnull value LAST

Discussão em 'Outras Linguagens' iniciado por Stack, Outubro 9, 2024 às 19:02.

  1. Stack

    Stack Membro Participativo

    When I discovered NULLS LAST, I kinda hoped it could be generalised to 'X LAST' in a CASE statement in the ORDER BY portion of a query.

    Not so, it would seem.

    I'm trying to sort a table by two columns (easy), but get the output in a specific order (easy), with one specific value of one column to appear last (got it done... ugly).

    Let's say that the columns are zone and status (don't blame me for naming a column zone - I didn't name them). status only takes 2 values ('U' and 'S'), whereas zone can take any of about 100 values.

    One subset of zone's values is (in pseudo-regexp) IN[0-7]Z, and those are first in the result. That's easy to do with a CASE.

    zone can also take the value 'Future', which should appear LAST in the result.

    In my typical kludgy-munge way, I have simply imposed a CASE value of 1000 as follows:

    group by zone, status
    order by (
    case when zone='IN1Z' then 1
    when zone='IN2Z' then 2
    when zone='IN3Z' then 3
    .
    . -- other IN[X]Z etc
    .
    when zone = 'Future' then 1000
    else 11 -- [number of defined cases +1]
    end), zone, status


    This works, but it's obviously a kludge, and I wonder if there might be one-liner doing the same.
    Is there a cleaner way to achieve the same result?

    Continue reading...

Compartilhe esta Página