如何按一列排序,但如何基于非数字的另一列进行排序?

时间:2019-06-13 17:12:11

标签: sql-server ranking-functions

我尝试对四列进行排名。它们需要按员工ID分组,然后按订单编号从低到高列出。然后,当一切正常时,我实际上是在尝试按该顺序排列城市的排名。如果在同一座城市的同一城市之后列出了同一名员工,那么我希望那些排名相同。

下表的示例如下。顺序是正确的,但是排名不符合我要尝试的水平。

Name            Employee_ID     Order_Number     City       Rank   
John               1                1            Boston       1  
John               1                2            Boston       2  
Will               2                1            Peabody      1  
Will               2                2            Weston       2   
Will               2                3            Newton       3



select Name, Employee_ID, Order_Number, City,
dense_rank() over(partition by Employee_ID order by Order_Number) as rank
from #Employee

我实际希望的结果是:

Name            Employee_ID     Order_Number     City       Rank   
John               1                1            Boston       1  
John               1                2            Boston       1  
Will               2                1            Boston       1  
Will               2                2            Weston       2   
Will               2                3            Newton       3  

然后,我最终将删除重复的城市,最终得到:

Name            Employee_ID     Order_Number     City       Rank   
John               1                1            Boston       1  
Will               2                1            Boston       1  
Will               2                2            Weston       2   
Will               2                3            Newton       3

2 个答案:

答案 0 :(得分:0)

您可以尝试以下脚本来获取所需的输出。

this.txtDefault.ShouldReturn += (textField) => {
textField.ResignFirstResponder();
return true;
};

结果集的输出是-

SELECT Name, Employee_ID, Order_Number, City ,
ROW_NUMBER() OVER (PARTITION BY Employee_ID ORDER BY Order_Number) rank
(
    select Name, Employee_ID, Order_Number, City,
    dense_rank() over(partition by Employee_ID,city order by Order_Number) as rank
    from #Employee
)A
WHERE rank = 1

Fiddle上检查脚本的输出。

答案 1 :(得分:0)

您可以使用Bitmap Heap Scan on cache (cost=12.15..1387.51 rows=364 width=585) (actual time=53.794..87.802 rows=71634 loops=1) Recheck Cond: ((((data -> 'Info'::text) ->> 'Date'::text) >= '2018-01-01'::text) AND (((data -> 'Info'::text) ->> 'Date'::text) <= '2020-12-01'::text) AND (((data -> 'Info'::text) ->> 'Condition'::text) = '3'::text)) Heap Blocks: exact=16465 -> Bitmap Index Scan on cache_data_index (cost=0.00..12.06 rows=364 width=0) (actual time=51.216..51.216 rows=71634 loops=1) Index Cond: ((((data -> 'Info'::text) ->> 'Date'::text) >= '2018-01-01'::text) AND (((data -> 'Info'::text) ->> 'Date'::text) <= '2020-12-01'::text)) Planning Time: 0.247 ms Execution Time: 90.586 ms 检查以前的城市是否相同。如果先前的城市不同或为空,则我们按原样进行排名;如果城市相同,则排名-1为我们提供与上一行相同的数字。 Demo

LAG()