null最后如何排序的 |
您所在的位置:网站首页 › 舞者最后排名怎么排 › null最后如何排序的 |
说该问题之前简单过一下语法 (会的可以直接跳过 语法: row_number() over(partition by column1 order by column2) 表示根据COL1分组,在分组内部根据 COL2排序,而此函数计算的值就表示每组内部排序后的顺序编号,默认升序排列,如果想降序 order by column2 desc 今日重点:row_number 我们常用来排序/但是数据里有NULL的时候NULL会在hivesql中默认为最小值,并不会忽略。来看下这个情况: 假设场景: 统计商店每天进来的人数,把结果按照日期从小到大排序,如果这天商店关门了即人数为NULL,但是仍然有日期。 你有的数据:人数和日期 你想要的结果是: 问题: 当数据里有NULL,你想要两列排序 一列全部排序 一列剔除NULL的排序 两列要并列存在,你会怎么处理呢? 首先:算出时间从小到达的rn_all(不管null select num,date, row_number() over(order by date) rn_all from xxxxx.test_rownumber剔除null再次排序 - 尝试1: 思路:当人数num非空的时候去排序,否则直接给NULL;这样听起来是不是有点对 select num, date, case when num is not null then row_number() over(order by date) else NULL end rn_not_NULL from xxxxx.test_rownumber结果: 排序怎么少了1和5,发现它是先排序再剔除的,剔除的虽然是num 为空的数值,但是剩下的排序是剔除前的排序哈哈。排序无效。 剔除null再次排序 - 尝试2: 思路:num为空对应的date先变成NULL 再排序 select num,date,date_not_NULL, row_number() over(order by date) rn, row_number() over(order by date_not_NULL) rn_not_NULL from(select num, date, #新列一个date_not_null 的列,把num是NULL的对应date也变成null case when num is not NULL then date else NULL end date_not_NULLfrom facade_qe_tmp_table.test_rownumber) t问题:NULL会参与排序!!!!!!并且系统会把NULL自动识别成最小的数进行排序,放在开始,看上图的结果NULL排在12序列 思考:其实我们只要把null放在最后就不会影响其他数的排序。 剔除null再次排序 - 尝试3: 思路:给非NULL的数标上1,null的数标0,排序的时候先根据01排,非NULL的数放在前面,然后再去根据时间排序 select num, date, rn_01, row_number() over(order by date) rn, row_number() over(order by rn_01,date) rn_not_null FROM(select num, date,case when num is not NULL then 0 else 1 end rn_01 from facade_qe_tmp_table.test_rownumber) tNULL被我们放在了最后, 这时候只要剔除它就好了 比如 select num, date, rn_01, row_number() over(order by date) rn, case when num is not NULL then row_number() over(order by rn_01,date) else NULL end rn_not_nullFROM(select num, date, case when num is not NULL then 0 else 1 end rn_01from facade_qe_tmp_table.test_rownumber) tEND 也许有一天你会有同样的问题哈哈 这里只是hivesql对null的默认情况 不是所有的数据库处理都把NULL默认为最小 先备案一下 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |