使用GROUP BY仅显示每个用户的最新更新行

时间:2015-10-22 17:57:32

标签: sql sql-server sql-server-2008 group-by

我一直无法找出执行GROUP BY的语法,只显示每个用户最新ups.db_LastUpdate的行(db_UserId)。

SELECT up.db_FirstName, up.db_LastName, up.db_UserId, ups.db_Initials, ups.db_LastUpdate 
FROM tblUserProfile up
    JOIN tblUserSel ups
        ON ups.db_Code = up.db_UserId
WHERE ups.db_UserTech = 'U'

输出(将有数百名用户,但你明白了这一点):

Jeff | Ledger | 1-34 | JL | 2015-08-11
Jeff | Ledger | 1-34 | DBC | 2015-06-06
Jeff | Ledger | 1-34 | YX | 2015-08-01
John | Barker | 1-26 | JR | 2015-04-04
John | Barker | 1-26 | YY | 2015-02-18
John | Barker | 1-26 | FF | 2015-11-14

也许像GROUP BY ups.dbUserId, MAX(db_LastUpdate)

感谢您的帮助

2 个答案:

答案 0 :(得分:7)

使用Boolean

ROW_NUMBER

正如评论中所指出的,您可以使用;WITH CTE AS ( SELECT up.db_FirstName, up.db_LastName, up.db_UserId, ups.db_Initials, ups.db_LastUpdate, RN = ROW_NUMBER() OVER(PARTITION BY up.db_UserId ORDER BY ups.db_LastUpdate DESC) FROM tblUserProfile up INNER JOIN tblUserSel ups ON ups.db_Code = up.db_UserId WHERE ups.db_UserTech = 'U' ) SELECT * FROM CTE WHERE RN = 1; 然后加入您的表格:

MAX

但是你需要知道,如果同一个用户存在一个具有相同日期的行,那么你将获得这两行。

答案 1 :(得分:0)

如果你的表有一个唯一的ID列,我通常会处理这样的情况:

WITH LastEdit AS (
    SELECT ups.db_Code, ups.db_Initials, ups.db_LastUpdate
    FROM tblUserSel ups
    WHERE ups.db_UserTech = 'U' AND ups.ID = (
        SELECT TOP 1 ID
        FROM tblUserSel upsn
        WHERE ups.db_Initials = upsn.db_Initials
        ORDER BY upsn.db_LastUpdate DESC
    )
)
SELECT up.db_FirstName, up.db_LastName, up.db_UserId, le.db_Initials, le.db_LastUpdate 
FROM tblUserProfile up
    INNER JOIN LastEdit le
        ON le.db_Code = up.db_UserId