T-SQL:使用CTE选择最大年份,然后选择最大序列

时间:2018-12-10 20:51:47

标签: sql-server tsql

我正在尝试根据年份和顺序号选择表格中的最大图片项,以便可以使用正确的图片文件名更新第二张表格。在下面的示例中,序列#2005765是正确的图像文件。

Image Table

我试图通过以下方式做到这一点:

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

1 个答案:

答案 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;