SQL 服务器 - select 来自外键的最小日期和 ID

SQL Server - select min date and id from foreign key

这些是我的表格:

用户:

id_user      name            email               last_access         id_company
  1        jhonatan       abc@abc.com            2014-12-15             1
  2         cesar          cef@cef.com           2014-12-31             1
  3         john          123@123.com            2015-01-09             2
  4         steven       897@asdd.cpom           2015-01-02             2
  5         greg           sd@touch.com          2014-12-07             1
  6          kyle           fb@fb.com            2014-11-20             1

公司:

id_company                company
   1                      Facebook
   2                      Appslovers

我需要知道,每个公司(只有一个)有哪些用户具有 MIN last_access。可能是这样的:

id_user              name              last_access              company
  6                  kyle              2014-11-20               Facebook
  4                 steven             2015-01-02              Appslovers

可能吗?

这可以通过多种方式完成,例如使用 window 函数(如 row_number )对数据进行分区,然后从每个组中选择最上面的行,如下所示:

;with cte (id_user, name, last_access, company, seq) as (
    select 
       id_user, 
       name, 
       last_access, 
       company, 
       seq = row_number() over (partition by u.id_company order by last_access) 
    from [user] u
    inner join [company] c on u.id_company = c.id_company
)

select id_user, name, last_access, company  
from cte where seq = 1

使用window function

SELECT id_user,
       NAME,
       last_access,
       company
FROM   (SELECT id_user,
               NAME,
               last_access,
               company,
               Row_number()OVER(partition BY company ORDER BY last_access) rn
        FROM   users u
               JOIN company c
                 ON u.id_company = c.id_company) a
WHERE  rn = 1 

join table 都找到每个 company 的最小 last_access 日期,然后将结果加入 users table 得到结果

SELECT id_user,
       NAME,
       a.last_access,
       a.company
FROM   users u
       JOIN(SELECT u.id_company,
                   Min(last_access) last_access,
                   company
            FROM   users u
                   JOIN company c
                     ON u.id_company = c.id_company
            GROUP  BY u.id_company,
                      company) a
         ON a.id_company = u.id_company
            AND u.last_access = a.last_access