SQL Server:如何在多个Select中获取行号

时间:2018-05-07 20:18:04

标签: sql sql-server tsql

当我使用Multiple Select

时出错错误行号

First Query获得正确的行号

SELECT num
FROM (SELECT ItemId, CommentId,ROW_NUMBER() OVER (ORDER BY CreatedDate desc) AS num
      From ItemComments
      where ItemId = 10
    ) AS numbered
WHERE numbered.CommentId =100

Scond Query获得正确的行号

SELECT num
FROM (SELECT ItemId, CommentId, ROW_NUMBER() OVER(ORDER BY CreatedDate desc) AS num
      From ItemComments
      where ItemId = 20
    ) AS numbered
WHERE numbered.CommentId =200

当我尝试在一个查询中使用上述两个值时,行号错误

第三个查询错误的行号

SELECT num
FROM (SELECT ItemId, CommentId, ROW_NUMBER() OVER(ORDER BY createddate desc) AS num
      From ItemComments
      where ItemId in(20,10)
     ) AS numbered
WHERE numbered.CommentId in (200, 100)

请帮我在多选

中获取正确的行号

谢谢

enter image description here

1 个答案:

答案 0 :(得分:2)

您只需要partition by

SELECT num
FROM (SELECT ItemId, CommentId,
            ROW_NUMBER() OVER (PARTITION BY ItemId ORDER BY createddate desc) AS num
      From ItemComments
      where ItemId in (20, 10)
     ) numbered
WHERE numbered.CommentId in (200, 100)