last_value分区

时间:2015-05-07 03:20:57

标签: sql

Select speed, ram, price, 
       last_value(price) over (partition by speed, ram order by speed, ram) as lastp 
from PC

PC表

code    model   speed   ram  hd     cd  price

 1      1232    500     64   5.0    12x 600.0000
 10     1260    500     32   10.0   12x 350.0000
 11     1233    900     128  40.0   40x 980.0000
 12     1233    800     128  20.0   50x 970.0000
 2      1121    750     128  14.0   40x 850.0000
 3      1233    500     64   5.0    12x 600.0000
 4      1121    600     128  14.0   40x 850.0000
 5      1121    600     128  8.0    40x 850.0000
 6      1233    750     128  20.0   50x 950.0000
 7      1232    500     32   10.0   12x 400.0000
 8      1232    450     64   8.0    24x 350.0000
 9      1232    450     32   10.0   24x 350.0000


speed   ram price       lastp

450     32  350.0000    350.0000
450     64  350.0000    350.0000
500     32  350.0000    350.0000
500     32  400.0000    350.0000

任何人都可以解释为什么速度500 ram 32 lastp是350而不是400

1 个答案:

答案 0 :(得分:1)

您可以根据主查询进行另一次查询。我不知道您的dbms,但您可以在大多数数据库中尝试这一点。

;WITH C AS(
Select speed, ram, price,
        ROW_NUMBER() over (partition by speed, ram order by speed, ram) as Rn
from tbl
)
SELECT speed, ram, price
  ,LAST_VALUE(price) over (partition by speed, ram order by speed , ram) as lastp
  FROM C
ORDER BY speed, ram, Rn DESC

SQLFiddle for SQL Server