2013-09-26 33 views
4

我有一个使用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 

我应该使用类似等级()???

我使用Teradata的

+1

['PIVOT'(http://technet.microsoft.com/en-us/library/ms177410的.aspx(V = SQL.100)) –

+0

我试图做到这一点的SQL,我在Teradata的工作 –

+0

看看如何使用Teradata的[这里] [1] [1]枢:http://stackoverflow.com/questions/14837996/sql-rows-into- columns-pivot-table – Vulcronos

回答

2

您可以添加两个窗口的功能来获得第二和第三高的价格,这应该在同一个STAT步作为当前ROW_NUMBER运行,所以没有额外的开销:

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 
+0

当我尝试应用这个时,我收到一条消息,说''Price2'和'over'关键字 –

+0

之间有一段期望值,当你剪切并粘贴时,会发生这种情况。 – dnoeth

+0

我在'over'之前放置'price2'。所以它现在与结果。但是,我只是每次都得到最大值。因为资格只会要求最高的结果。我需要得到三个不同的结果。那可能吗? @dnoeth –

0

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

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