Implementing NULLS FIRST in Amazon Redshift

空扰寡人 提交于 2020-01-17 03:13:05

问题


I am using sum window function for row number, similar to this query -

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;

The problem is that if field_c is a null value, it appears at the end. I want it at the beginning, so null value is treated as smaller than all other values. In Oracle, this could be done by providing NULLS FIRST argument, but its not supported in Redshift. So how do I implement it in Redshift ?


回答1:


I want it [null] at the beginning, so null value is treated as smaller than all other values.

Use the expression

field_c IS NOT NULL

as first ORDER BY item. It evaluates to ...
FALSE .. if NULL
TRUE .. if NOT NULL.

And FALSE (0) sorts before TRUE (1). Works for any data type and any possible distribution of values.

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:


If field_c is string

order by coalesce(field_c, '')

If numeric

order by coalesce(field_c, 0)

Replace the zero with the lowest possible value



来源:https://stackoverflow.com/questions/22295892/implementing-nulls-first-in-amazon-redshift

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