需求:有一利率表BBFMCDRT,表结构:
CDDPTY, --业务种类
CCY, --币种
TXDT,--日期
CDYRAT --利率
K CDDPTY
K CCY
K TXDT
现要求用一条SQL SELECT出当前利率(CDYRAT),即最近日期的利率,且同时select 出cddpty,ccy
如直接用GROUP BY CDDPTY,CCY 无法select 出cdyrat
方法1:
group by后在inner join自己本身,从而带出需要带出的字段
SELECT A.CDDPTY CDDPTY,
A.CDCURR CDCURR,
A.CDVLDT CDVLDT,
A.CDYRAT CDYRAT
FROM BBFMCDRT A
INNER JOIN
(SELECT B.CDDPTY,
B.CDCURR,
MAX(B.CDVLDT) CDVLDT
FROM BBFMCDRT B
GROUP BY B.CDDPTY, B.CDCURR
) C ON A.CDDPTY = C.CDDPTY
AND A.CDCURR = C.CDCURR
AND A.CDVLDT = C.CDVLDT
方法2:
用分析函数
SELECT DISTINCT T.CDDPTY,T.CDCURR,
FIRST_VALUE(T.CDYRAT) OVER(PARTITION BY T.CDCURR,T.CDDPTY ORDER BY T.CDVLDT DESC) CDYRAT
FROM BBFMCDRT T