有几种方法可以做到这一点。这是一个带有子查询和的ROWNUM
:
SELECT *
FROM (
SELECT pv.version, pv.vin, pv.policyid, pv.segeffdate, pv.segexpdate, pv.changenum
FROM nsa_al.polvehicle pv
WHERE pv.vin = '2GTEC19T011201788'
AND pv.changenum > 0
ORDER BY pv.version DESC
) t
WHERE ROWNUM = 1
这只会返回一条记录。如果您需要领带,您可以改用分析功能RANK()
。
SELECT *
FROM (
SELECT RANK() OVER (ORDER BY version DESC) rnk, pv.version, pv.vin, pv.changenum
FROM pv
WHERE pv.vin = '2GTEC19T011201788'
AND pv.changenum > 0
ORDER BY pv.version DESC
) t
WHERE rnk = 1
如果您更喜欢使用MAX
聚合,那么最简单的方法是使用公用表表达式和JOIN
表本身。如果有多个具有相同版本的记录,这可能会产生多个结果:
WITH CTE AS (
SELECT pv.version, pv.vin, pv.changenum
FROM pv
WHERE pv.vin = '2GTEC19T011201788'
AND pv.changenum > 0
)
SELECT *
FROM CTE C
JOIN (
SELECT MAX(version) maxVersion
FROM CTE) C2 ON C.version = C2.maxVersion