如何获得MASTER条目的最新DETAIL条目?

时间:2015-09-27 10:55:17

标签: sql sql-server sql-server-2008 greatest-n-per-group

我有2张桌子

1。用户大师 user_id,user_full_name,user_dob ......等等

2。登录详细信息 login_id,login_user_id,login_time,login_date,logout_time

问题

第二个表对用户主表id

有n行

我需要进行连接,但条件是它应该只显示用户的最后登录数据

示例 user_full_name,user_login,user_logout等......

3 个答案:

答案 0 :(得分:2)

如果您想要单个用户的结果,可以使用简单的INNER JOIN结合ORDER BYTOP 1

SELECT TOP 1 user_full_name, login_time, login_date, logout_time
FROM Users INNER JOIN Logins ON
  Users.user_id = Logins.user_id
WHERE
  Users.user_id = @user_id
ORDER BY login_date DESC, login_time DESC

(见SQLFiddle

如果您想要所有用户的结果,可以使用CROSS APPLY

SELECT user_full_name, l.*
FROM Users u CROSS APPLY (
  SELECT TOP 1 login_time, login_date, logout_time
  FROM Logins
  WHERE
    u.user_id = Logins.user_id
  ORDER BY login_date DESC, login_time DESC
  ) l

(见SQLFiddle

答案 1 :(得分:1)

此问题的常见解决方案是使用row_number窗口函数并过滤每个分区中行号为1的行(按用户排序,按日期/时间排序):

WITH UserDetails AS (
    SELECT 
       *
       , ROW_NUMBER() OVER (PARTITION BY login_user_id 
                            ORDER BY login_date DESC, login_time DESC) AS RN
    FROM LoginDetails
)
SELECT * 
FROM UserMaster  M
JOIN UserDetails D ON M.user_id = D.login_user_id
WHERE D.RN = 1;

答案 2 :(得分:1)

您可以尝试在JOIN子句中使用TOP 1:

SELECT a.user_id, a.user_full_name, b.login_id...
FROM UserMaster a INNER JOIN Logins b ON b.login_date =
(
    SELECT  TOP 1 login_date 
    FROM    Logins 
    WHERE   login_user_id = a.user_id
    ORDER BY login_date DESC
)