SQL - 想为同一组值提供唯一的排名吗?

时间:2016-02-19 18:08:04

标签: sql rank window-functions

我需要帮助确定我尝试生成唯一标识符列的日期的最后更改价格,因此我可以将分区应用于此新列并在我的编程中派生其他逻辑。 你能帮我推导一下Unique-Identifier专栏吗?

Date        | OrderID   | Price | Seq_no |Unique-Indentifier  
1/24/2015   |   568956  |   300 |   1    |  1  
1/20/2015   |   568956  |   350 |   1    |  2  
1/20/2015   |   568956  |   375 |   2    |  3  
1/20/2015   |   568956  |   400 |   3    |  4  
1/17/2015   |   568956  |   400 |   1    |  4  
1/14/2015   |   568956  |   500 |   1    |  5  
1/11/2015   |   568956  |   500 |   1    |  5  
1/9/2015    |   568956  |   400 |   1    |  6  
1/7/2015    |   568956  |   400 |   1    |  6  
1/24/2015   |   568957  |   600 |   1    |  7  
1/20/2015   |   568957  |   600 |   1    |  7  
1/17/2015   |   568957  |   700 |   1    |  8  
1/14/2015   |   568957  |   800 |   1    |  9  
1/11/2015   |   568957  |   800 |   1    |  9  
1/9/2015    |   568957  |   700 |   1    |  10  
1/7/2015    |   568957  |   700 |   1    |  10  

我无法在价格列上应用分区。原因:对于OrderID'568956',在两个不同的日期设置相同的价格400。我想隔离这两套。如果我只是在Price Column上使用分区,那么我将把所有四行作为一组。所以我需要设置一些标识符来区分这些行,并在我的新列'UniqueIdentifier'上应用分区。

Set 1:  
1/20/2015            568956  400         4    
1/17/2015            568956  400         4


Set 2:   
1/9/2015              568956  400         6    
1/7/2015              568956  400         6   

如果我应用分区,我将结果作为一组 - 我不期望。

Set 1:  
1/20/2015             568956  400         4    
1/17/2015             568956  400         4     
1/9/2015              568956  400         4    
1/7/2015              568956  400         4

2 个答案:

答案 0 :(得分:0)

在您的select语句中执行以下操作:

SELECT
DISTINCT
    ROW_NUMBER() OVER(PARTITION BY Date,OrderID,Price ORDER BY Date DESC) AS RowNum
    ,Date
    ,OrderID
    ,Price

您可能不得不使用PARTITION BY部分,这取决于您的select语句的工作方式,但是当我使用它时,它会返回每个值的唯一行号。

我不确定您是否能够准确ORDER BY该日期值,因此您可能需要将其转换为DATETIME

答案 1 :(得分:0)

您需要识别组,然后分配序号。一种方法是行数的差异。我认为这是逻辑:

select t.*,
       dense_rank() over (partition by orderid order by grp, price) as newcol
from (select t.*,
             (row_number() over partition by orderid order by date, seq_no) -
              row_number() over partition by orderid, price order by date, seq_no)
             ) as grp
      from t
     ) t