MySQL计算排名并更新原始表

时间:2014-09-09 17:13:31

标签: mysql sql

MySQL服务器5.6.20(目前是最新版本)

根据日期表给出价格。我添加了一个新列“排名”,它代表按日期排列的项目价格。

Date      Item  Price  Rank
1/1/2014  A     5.01   0  
1/1/2014  B     31     0  
1/1/2014  C     1.5    0  
1/2/2014  A     5.11   0  
1/2/2014  B     20     0  
1/2/2014  C     5.5    0  
1/3/2014  A     30     0  
1/3/2014  B     11.01  0  
1/3/2014  C     22     0  

如何编写SQL语句来计算排名并更新原始表?下面是填写了排名的预期表。排名计算按日期分组(1 / 1,1 / 2,1 / 3等)。

Date      Item  Price  Rank
1/1/2014  A     5.01   2  
1/1/2014  B     31     1  
1/1/2014  C     1.5    3  
1/2/2014  A     5.11   3  
1/2/2014  B     20     1  
1/2/2014  C     5.5    2  
1/3/2014  A     30     1  
1/3/2014  B     11.01  3  
1/3/2014  C     22     2  

此外,如果几个项目的价格相同,MySQL将如何处理排名?例如:

Date      Item  Price  Rank
1/4/2014  A     31     0  
1/4/2014  B     31     0  
1/4/2014  C     1.5    0  

感谢。

2 个答案:

答案 0 :(得分:3)

您可以使用变量获取查询中的排名:

  select t.*,
         (@rn := if(@d = date, @rn + 1,
                    if(@d := date, 1, 1)
                   )
         ) as rank
  from pricebydate t cross join
       (select @d := NULL, @rn := 0) vars
  order by date, price desc;

您可以使用update

将其放在join
update pricebydate pbd join
       (select t.*,
             (@rn := if(@d = date, @rn + 1,
                        if(@d := date, 1, 1)
                       )
             ) as rank
        from pricebydate t cross join
             (select @d := NULL, @rn := 0) vars
        order by date, price desc
       ) r
       on pbd.date = r.date and pbd.item = item
    set pbd.rank = r.rank;

答案 1 :(得分:0)

我相信这会完全符合您的要求:

Update YourTable As T1                                   
Set    ItemRank = (                                               
    Select ItemRank From (                                         
        Select Rank() Over (Partition By ItemDate Order By Price Desc) 
        As ItemRank, Item, ItemDate                                    
        From YourTable                                            
    ) As T2                                                        
    Where T2.Item = T1.Item                                        
    And   T2.ItemDate = T1.ItemDate                                
)                                                              

重复排名将被视为具有相同排名。