1

使用 T-SQL 我有 2 个表,其中一个列出了所有成员(recEntrants)。第二个表(recEntrantStatus)包含每个成员的状态更新。目前我有以下 SQL 来检索所有成员的所有更新。

SELECT EN.Id, EN.artistName, GR.genre, ES.lastModifiedOn, EN.voteStatus, 
ES.notified
FROM recEntrantStatus AS ES
JOIN recEntrants AS EN
ON ES.entrantId = EN.Id
JOIN recGenre AS GR
ON EN.genreId = GR.Id
AND ES.judgeId = @judgeId
AND ES.roundId > 0
ORDER BY ES.voted DESC, ES.roundId, EN.Id

新增以下要求:

SELECT EN.Id, EN.artistName, GR.genre, ES.lastModifiedOn, EN.voteStatus, 
ES.notified
FROM recEntrantStatus AS ES
LEFT JOIN recEntrants AS EN
ON ES.entrantId = EN.Id
LEFT JOIN recGenre AS GR
ON EN.genreId = GR.Id
WHERE ES.roundId = 2

但是,我需要实现的是为每个成员提取最新的状态更新/记录。

Ps 我在 recEntrantStatus 上有一个 modifiedDate 列

对此的任何帮助将不胜感激。

提前致谢。

4

3 回答 3

1

使用row_number() 结束 (partition by ES.entrantId order by ES.lastModifiedOn desc)。如果您仍需要使用相同的顺序,请在子查询中添加 Order by column list。此外,如果您需要选择NO status records使用 aLEFT JOIN而不是 a 的记录JOIN

SELECT * FROM (
    SELECT EN.Id, EN.artistName, GR.genre, ES.lastModifiedOn, EN.voteStatus, 
       ES.notified,
       row_number() over (partition by ES.entrantId order by ES.lastModifiedOn desc) rn 
    FROM recEntrantStatus AS ES
    JOIN recEntrants AS EN
        ON ES.entrantId = EN.Id JOIN recGenre AS GR
        ON EN.genreId = GR.Id AND ES.judgeId = @judgeId AND ES.roundId > 0
) A
WHERE A.rn = 1
--ORDER BY A.voted DESC, A.roundId, A.Id

编辑(根据 OP 编辑​​):

SELECT * FROM (
    SELECT ES.entrantId Id, EN.artistName, GR.genre, ES.lastModifiedOn, EN.voteStatus, 
       ES.notified,
       row_number() over (partition by ES.entrantId order by ES.lastModifiedOn desc) rn 
    FROM recEntrantStatus AS ES
    LEFT JOIN recEntrants AS EN
        ON ES.entrantId = EN.Id LEFT JOIN recGenre AS GR
        ON EN.genreId = GR.Id 
    --AND ES.judgeId = @judgeId 
    WHERE ES.roundId = 2
) A
WHERE A.rn = 1
于 2013-01-31T16:26:27.480 回答
0

如果不添加 ModifiedDate 列,则无法执行此操作,该列将包含该列的修改日期和时间。然后你可以这样做:

select * from tableA where whatever='whatever' order by ModifiedDate desc.

此外,您可能希望查看每次更新或插入发生时都会修改此列的插入/更新触发器。

但是,如果您只想要第一个条目,则需要TOP()

于 2013-01-31T16:14:28.443 回答
0

试试这个:

;WITH MostRecent
AS
(
    SELECT 
        ROW_NUMBER() OVER (PARTITION BY entrantId ORDER BY lastModifiedOn DESC) RN,
        entrantId,
        judgeId,
        roundId,
        voted 
    FROM recEntrantStatus
)
SELECT
    EN.Id,
    EN.artistName,
    GR.genre,
    ES.lastModifiedOn,
    EN.voteStatus, 
    ES.notified
FROM MostRecent AS ES
    JOIN recEntrants AS EN
ON ES.entrantId = EN.Id
    JOIN recGenre AS GR
ON EN.genreId = GR.Id
   AND ES.judgeId = @judgeId
   AND ES.roundId > 0
WHERE ES.RN = 1
ORDER BY ES.voted DESC, ES.roundId, EN.Id
于 2013-01-31T16:18:26.493 回答