PostgreSQL: order by column, with specific NON-NULL value LAST

我怕爱的太早我们不能终老 提交于 2019-12-22 14:50:14

问题


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?


回答1:


Postgres allows boolean values in the ORDER BY clause, so here is your generalised 'X LAST':

ORDER BY (my_column = 'X')

The expression evaluates to boolean, resulting values sort this way:

FALSE (0)
TRUE (1)
NULL

Since we deal with non-null values, that's all we need. Here is your one-liner:

...
ORDER BY (zone = 'Future'), zone, status;

Related:

  • Sorting null values after all others, except special
  • Select query but show the result from record number 3
  • SQL two criteria from one group-by



回答2:


I'm not familiar postgreSQL specifically, but I've worked with similar problems in MS SQL server. As far as I know, the only "nice" way to solve a problem like this is to create a separate table of zone values and assign each one a sort sequence.

For example, let's call the table ZoneSequence:

Zone   | Sequence
------ | --------
IN1Z   |        1
IN2Z   |        2
IN3Z   |        3
Future |     1000

And so on. Then you simply join ZoneSequence into your query, and sort by the Sequence column (make sure to add good indexes!).

The good thing about this method is that it's easy to maintain when new zone codes are created, as they likely will be.



来源:https://stackoverflow.com/questions/32193339/postgresql-order-by-column-with-specific-non-null-value-last

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!