SELECT
ass.assessmentAmount -- want to fetch assessmentAmount of min(ass.assessmentId)
ass.assessmentId
FROM
--bunch of joins
WHERE
ass.assessmentId = (SELECT min(ass2.assessmentId) FROM Assessment ass2
--same bunch of joins
它看起来很混乱,因为我有六个条件加入,我不想重复两次。还有另一种方法吗?
答案 0 :(得分:3)
使用MIN( ass.assessmentId ) OVER ()
分析函数:
SELECT *
FROM (
SELECT ass.assessmentAmount,
ass.assessmentId,
MIN( ass.assessmentId ) OVER () AS min_assessmentId
FROM --bunch of joins
)
WHERE assessmentId = min_assessmentId;
您还可以使用RANK()
:
SELECT *
FROM (
SELECT ass.assessmentAmount,
ass.assessmentId,
RANK() OVER ( ORDER BY ass.assessmentId ) AS rnk
FROM --bunch of joins
)
WHERE rnk = 1;
如果assessmentId
为UNIQUE
,并且只能将一行作为最低限度,那么您可以将RANK
替换为ROW_NUMBER
;但是,您也可以使用ROWNUM
伪列来获得所需的结果:
SELECT *
FROM (
SELECT ass.assessmentAmount,
ass.assessmentId
FROM --bunch of joins
ORDER BY ass.assessmentId ASC
)
WHERE ROWNUM = 1;
答案 1 :(得分:1)
使用带有row_number的CTE
with CTE as
(
select assessmentId,
assessmentAmount ,
row_number() over (order by assessmentid asc) as rn
from --bunch of joins
)
select *
from CTE
where rn = 1