选择每个成员的最新记录

时间:2013-01-31 16:10:07

标签: sql-server sql-server-2008 tsql stored-procedures

使用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

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

P.S。我在recEntrantStatus上有一个modifiedDate列

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

提前致谢。

3 个答案:

答案 0 :(得分:1)

使用row_number() over (partition by ES.entrantId order by ES.lastModifiedOn desc)。如果您仍需要使用相同的订单,请按列列表添加到子查询。此外,如果您需要选择拥有NO status records的记录,请使用LEFT JOIN代替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

答案 1 :(得分:0)

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

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

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

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

答案 2 :(得分: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