我有一张桌子
CMPI_CODE CMI_CODE CMN_CDTY_MTRL CMPI_PRICE_TYPE TRM_CODE ENTRY_DATE USR_CODE CMPI_PRCINX CMPI_ID_REF CMPI_UPDATE_STS CMPI_EFF_DATE
---------- ---------- ------------- --------------- ---------- ---------- ---------- ----------- ----------- --------------- -------------
141 57 344 AL 26-MAY-14 0 88 135 N 14-MAY-14
135 57 344 AL 24-MAY-14 0 91 134 N 14-MAY-25
134 57 344 AL 24-MAY-14 0 90 132 N 14-MAY-01
132 57 344 PL 24-MAY-14 0 100 N 14-MAY-01
133 58 345 PL 24-MAY-14 0 55 N 14-MAY-01
我想获得Currnet_Price和Previous Price .. 我的尝试就是这个
SELECT
NTH_VALUE(CMPI_PRCINX,1) FROM LAST OVER (PARTITION BY CMI_CODE ORDER BY CMPI_CODE ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS cur,
NTH_VALUE(CMPI_PRCINX,2) FROM LAST OVER (PARTITION BY CMI_CODE ORDER BY CMPI_CODE ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS PREVIOUS_PRICE
FROM CMD_MTRL_PRICE_INF B
WHERE CMPI_CODE IN (SELECT MAX(CMPI_CODE) FROM CMD_MTRL_PRICE_INF GROUP BY CMI_CODE) ORDER BY CMPI_CODE
输出
CURRENT_PRICE PREVIOUS_PRICE
------------- --------------
55
88
但它应该显示一些像这样的东西
PREVIOUS_PRICE CURRENT_PRICE
-------------- -------------
55
91 88
需要一些帮助..
答案 0 :(得分:3)
您的WHERE子句在应用函数之前过滤掉除了具有max CMPI_CODE的行之外的所有行。因此,您的NTH_VALUE函数无法获取之前的值。
您可以简化它。
查询:
select cur, prev
from (
select CMPI_PRCINX cur,
lag(CMPI_PRCINX) over (partition by CMI_CODE order by CMPI_CODE) prev,
row_number() over (partition by CMI_CODE order by CMPI_CODE desc) r
from CMD_MTRL_PRICE_INF
)
where r = 1;
答案 1 :(得分:1)
试试这个
WITH
PRICEINFO AS(
SELECT B.*,
NTH_VALUE(CMPI_PRCINX,2) FROM LAST OVER (PARTITION BY CMI_CODE ORDER BY CMPI_CODE ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS PREVIOUS_PRICE
FROM CMD_MTRL_PRICE_INF B
)
SELECT PREVIOUS_PRICE,CMPI_PRCINX AS CURRENT_PRICE FROM PRICEINFO
WHERE CMPI_CODE IN (SELECT MAX(CMPI_CODE) FROM CMD_MTRL_PRICE_INF GROUP BY CMI_CODE) ORDER BY CMPI_CODE