sql – 在多个列上的分区上拆分row_number()

我有一个查询,它使用row_number()而不是分区.

当结果出来时,它看起来像

Product         Row_Number         Price
A               1                  25
A               2                  20
A               3                  15
B               1                  100
B               2                  10
B               3                  2

我希望得到的结果显示在列之类的

Product      Row1         Row2        Row3      price1       price2       price3
A            1            2           3         25           20           15
B            1            2           3         100          10           2

我应该使用像rank()这样的东西吗?

我正在使用Teradata

最佳答案 您可以再添加两个窗口函数来获得第二和第三高价格,这应该在与当前ROW_NUMBER相同的STAT步骤中运行,因此没有额外的开销:

select
   product,
   price as Price1,
   min(price)
   over (partition by product
         order by price desc
         rows between 1 following and 1 following) as Price2,
   min(price)
   over (partition by product
         order by price desc
         rows between 2 following and 2 following) as Price3
from tab
qualify 
   row_number() 
   over (partition by product
         order by price desc) = 1
点赞