【问题标题】:Implementing NULLS FIRST in Amazon Redshift在 Amazon Redshift 中实施 NULLS FIRST
【发布时间】:2014-03-10 09:05:21
【问题描述】:

我正在对行号使用求和窗口函数,类似于这个查询 -

SELECT field_a,
       SUM(1) OVER (PARTITION BY field_b ORDER BY field_c ASC ROWS UNBOUNDED PRECEDING) AS row_number
FROM test_table
    ORDER BY row_number;

问题是如果field_c是空值,它会出现在最后。我一开始就想要它,所以 null 值被视为小于所有其他值。在 Oracle 中,这可以通过提供 NULLS FIRST 参数来完成,但在 Redshift 中不支持。那么如何在 Redshift 中实现它呢?

【问题讨论】:

  • 为什么是sum(1) 而不是row_number()?首先是空值:您可以尝试order by coalesce(field_c, date '1900-01-01')
  • @a_horse_with_no_name Redshift 支持窗口函数吗?
  • @CraigRinger:显然sum(1) over (...) 似乎有效
  • @CraigRinger: Apparently, it does.

标签: sql postgresql null sql-order-by amazon-redshift


【解决方案1】:

我希望它以 [null] 开头,因此 null 值被视为小于所有其他值。

使用表达式

field_c IS NOT NULL

作为第一个 ORDER BY 项目。它的计算结果为 ...
FALSE .. if NULL
TRUE .. if NOT NULL。

FALSE (0) 排在TRUE (1) 之前。适用于任何数据类型和任何可能的值分布。

SELECT field_a,
       row_number() OVER (PARTITION BY field_b
                          ORDER BY field_c IS NOT NULL, field_c) AS row_number
FROM   test_table
ORDER  BY row_number;

【讨论】:

    【解决方案2】:

    如果field_c 是字符串

    order by coalesce(field_c, '')
    

    如果是数字

    order by coalesce(field_c, 0)
    

    用可能的最低值替换零

    【讨论】:

      猜你喜欢
      • 2017-11-02
      • 1970-01-01
      • 2020-11-02
      • 2010-11-30
      • 2016-12-30
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 2017-05-29
      相关资源
      最近更新 更多