SQL Server - 从外键中选择最小日期和id

时间:2015-01-11 04:42:46

标签: sql sql-server date select min

这些是我的表格:

USER:

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

COMPANY:

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

有可能吗?

2 个答案:

答案 0 :(得分: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两个表都找到每last_access的最小company日期,然后将结果加回users表以获得结果

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 

答案 1 :(得分:0)

这可以通过多种方式完成,例如使用像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