【问题标题】:Postgres: Order by Non Zeros ASC followed by Zeros and then NULLS LASTPostgres:按非零 ASC 排序,然后是零,然后是 NULLS LAST
【发布时间】:2023-04-06 03:43:02
【问题描述】:

我有一个 PG 数据库表价格。结构如下:

id    name    total_sales    created_at
1      A         0.0         2016-01-01
2      B         1.25        2016-01-01
3      C         8.17        2016-01-01
4      D         15.09       2016-01-01
5      E         0.0         2016-01-01
6      F         NULL        2016-01-01
7      G         2.25        2016-01-01
8      H         19.34       2016-01-01
9      I         47.91       2016-01-01
10     J         0.0         2016-01-01
11     K         NULL        2016-01-01
12     L         0.01        2016-01-01
13     M         5.11        2016-01-01
14     N         27.53       2016-01-01
15     O         3.53        2016-01-01

我需要的很简单。我想订购这样的记录:

值 > 0.0 的项目以升序排列在前,然后是 0.0 后为 NULLS LAST 的项目

简而言之,我需要按以下顺序使用 o/p:

1st: 12 => 0.01
2nd: 2 => 1.25,
3rd: 7 => 2.25,
4th: 15 => 3.53,
5th: 13 => 5.11,
6th: 3 => 8.17,
7th: 4 => 15.09,
8th: 8 => 19.34,
9th: 14 => 27.53,
10th: 9 => 47.91,
11th, 12th, 13th all 0.0
14th, 15th all NULLS

所以,到目前为止,我尝试了以下 SQL,但没有成功!

SELECT * FROM prices
ORDER BY CASE WHEN total_sales = 0.0 THEN 0 ELSE total_sales END ASC NULLS LAST

【问题讨论】:

    标签: sql postgresql select sql-order-by


    【解决方案1】:
    order by total_sales = 0 nulls last, total_sales
    

    falsetrue 之前的订单

    【讨论】:

    • 哇!!我认为这只能通过 Switch case 来实现。但是您提供的解决方案是整洁、清晰且符合要求的!最佳答案
    • 它简洁,但不直观,这可能是维护问题。标记逻辑(如果使用)。
    【解决方案2】:

    这里有三类值:

    1. 正值
    2. 空值

    这可以用case 表达式表示,您可以使用二级排序来按升序对正值进行排序:

    SELECT   *
    FROM     prices
    ORDER BY CASE WHEN total_sales > 0 THEN 1 
                  WHEN total_sales = 0 THEN 2
                  WHEN total_sales IS NULL THEN 3 -- Just for readability
             END ASC,
             total_sales ASC
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多