我正在尝试根据年份和顺序号选择表格中的最大图片项,以便可以使用正确的图片文件名更新第二张表格。在下面的示例中,序列#2005765是正确的图像文件。
我试图通过以下方式做到这一点:
WITH CTE (Year, ImageId, ImageSeq) AS
(
SELECT
MAX(Year),
Image_ID,
Image_Seq
FROM
PIMAGE
WHERE
Type = 'PHOTO'
GROUP BY
Image_ID, Image_Seq
)
SELECT
cp.RPID,
MAX(i.Sequence),
i.File_Name
FROM
CommProperty cp
LEFT OUTER JOIN
CTE ON CTE.ImageId = cp.RPID
INNER JOIN
PIMAGE i ON i.Image_ID = cte.ImageId
AND i.Year = cte.Year
AND i.Image_Seq = cte.ImageSeq
WHERE
cp.RPID = 16107
GROUP BY
cp.RPID, i.File_Name
答案 0 :(得分:2)
最简单的方法是使用row_number()
:
SELECT p.*
FROM (SELECT p.*,
ROW_NUMBER() OVER (PARTITION BY image_id ORDER BY year DESC, image_seq DESC) as seqnum
FROM PIMAGE p
WHERE p.Type = 'PHOTO'
) p
WHERE seqnum = 1;