将row_number()拆分为多个列上的分区

时间:2013-09-26 15:45:16

标签: sql teradata 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

2 个答案:

答案 0 :(得分:2)

您可以再添加两个窗口函数来获得第二和第三高价格,这应该与您当前的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

答案 1 :(得分:0)

我只是给每个排序参数排序方向,然后,它非常好用。没有使用分区。

SELECT TOP (5) ROW_NUMBER() OVER (ORDER BY SCHEME ASC,APPLICATION_DATE DESC,TRANSACTION_REF_NO ASC,APPLICATION_STATUS DESC)