SQL等级和分区

时间:2018-09-28 01:51:54

标签: sql window-functions

使用此查询

SELECT STC.*, rank() over (partition by service_id order by service_tracking_id desc) rnk
FROM pntt.ntt_service_tracking_curr stc
where service_id in 
('61NA', 

响应是

rnk service_id service_tracking_id
1   61NA    7112415
2   61NA    5202885
3   61NA    44427875
4   61NA    2390953
5   61NA    117139
6   61NA    117138
7   61NA    10586781

为什么要这样排名?它与Service_id的字段类型有关吗?是否需要将其强制转换为整数或与字段的长度有关?

1 个答案:

答案 0 :(得分:0)

因为service_tracking_id是一个字符串,所以顺序是字母而不是数字。

这是一种解决方法:

SELECT STC.*,
       rank() over (partition by service_id
                    order by length(service_tracking_id) desc, service_tracking_id desc  -- might be len
                    ) rnk

或者,将值强制转换为小数:

SELECT STC.*,
       rank() over (partition by service_id
                    order by cast(service_tracking_id as decimal(20, 2)) desc
                    ) rnk