创建为数据子集重新开始的row_number

时间:2014-06-23 05:12:41

标签: sql window-functions

我对我的最新一期很难过。这是我的数据的外观

    ID      Item      Price    Rank
    1        A            1.00     1
    2        A            2.00     2
    3        A            2.00     2
    4        A            4.00     3
    5        B            1.23     1
    6        B            2.24     2
    7        B            4.40     3

问题是当存在'tie'时(请参阅行id = 2和3),我希望它是:

    ID      Item      Price    Rank
    1        A            1.00     1
    2        A            2.00     2
    3        A            2.00     3
    4        A            4.00     4

我知道我可以用光标轻松地做到这一点,但我认为性能方面会很糟糕。我尝试使用像LAG和Row_Number这样的窗口函数,但是你仍在处理逐行决策。而且当我到达下一个项目时,我无法想出一种迭代方法,然后重新开始。

有人能想出更好的方法来处理这个而不是游标吗?遗憾的是,纠正源数据并不是一个真正的选择。

4 个答案:

答案 0 :(得分:0)

<强> Window Functions

您必须使用row_number()代替dense_rank() or rank()

select ID,Item,Price,row_number() over(order by Item,Price)
from Table1

答案 1 :(得分:0)

您正在寻找row_number()partition by条款:

select id, item, price, row_number() over (partition by item order by price, id) as rank
from table t;

答案 2 :(得分:0)

可以尝试以下查询:

SELECT ID, ITEM, PRICE, 
ROW_NUMBER() OVER 
(
    PARTITION BY ITEM 
    ORDER BY PRICE, ID
) AS RANK
FROM MY_TABLE;

这将为您输出:

ID   |   Item    |  Price      |Rank
1    |    A      |      1.00   |  1
2    |    A      |      2.00   |  2
3    |    A      |      2.00   |  3
4    |    A      |      4.00   |  4
5    |    B      |      1.23   |  1
6    |    B      |      2.24   |  2
7    |    B      |      4.40   |  3

答案 3 :(得分:0)

尝试,

 In which OrderBy you want


 select id, item, price, Row_Number() over (partition by item order by price, id) as     Row_Number,
    Dense_Rank() over (partition by item order by price, id) as Dense_Rank,
    Rank() over (partition by item order by price, id) as Rank
    from table YourTableName;
相关问题