Sql 连接两个表,并从第一个表中获取一些列,从第二个表中获取最大时间戳值

Sql 连接两个表,并从第一个表中获取一些列,从第二个表中获取最大时间戳值,sql,join,db2,max,left-join,Sql,Join,Db2,Max,Left Join,我有一张员工桌 empid empname status 1 raj active 2 ravi active 3 ramu active 4 dan active 5 sam inactive 我还有一张桌子叫“设施” empid timestamp 1 2014-12-28 1 2015-05-05 1 2015-06-05 2 2015-05-03 2 2015-0

我有一张员工桌

empid empname status
1     raj     active
2     ravi    active
3     ramu    active
4     dan     active
5     sam     inactive
我还有一张桌子叫“设施”

empid timestamp
1     2014-12-28 
1     2015-05-05 
1     2015-06-05 
2     2015-05-03 
2     2015-06-04 
3     2015-02-01
我希望我的结果是一样的

empid empname status lastusedts
1     raj     active 2015-06-05
2     ravi    active 2015-06-04
3     ramu    active 2015-02-01
4     dan     active null
因此,我必须加入我的employee表和facilities表,并通过获取最大时间戳来查找员工上次使用设施的时间,对于未使用该时间戳的员工,时间戳值应为null,并且只提取活动员工。 请帮助我在db2中编写此查询

SELECT employee.empid, employee.empname, employee.status,facilities.timestamp as lastusedts
FROM employee
INNER JOIN facilities
ON employee.empid=facilities.empid;

使用
分组依据
进行
左连接
,以查找
最大值
(时间戳):

或者,最大时间戳的相关子选择:

select e.empid, e.empname, e.status, max(timestamp) as lastusedts
from employee e
  left join facilities f on e.empid = f.empid
where e.status = 'active'
group by e.empid, e.empname, e.status
select e.empid, e.empname, e.status, (select max(timestamp) from facilities f
                                      where e.empid = f.empid) as lastusedts
from employee e
where e.status = 'active'

通用表表达式[CTE]是将问题分解为更简单的块的一种方法

with m as
(
  select empid
        ,max(timestamp) as lastusedts
    from facilities
    group by e.empid
)
select e.empid
      ,e.empname
      ,e.status
      ,m.lastusedts
  from employee e
  left join  m 
     on e.empid = m.empid
  where e.status = 'active'

通用表表达式[CTE]是将问题分解为更简单的块的一种方法

with m as
(
  -- get last timestamp per employee
  select empid
        ,max(timestamp) as lastusedts
    from facilities
    group by e.empid
)
-- report employee info with last timestamp
select e.empid
      ,e.empname
      ,e.status
      ,m.lastusedts
  from employee e
  left join  m 
     on e.empid = m.empid
  where e.status = 'active'

但是我想要时间戳的最大值(即用户上次使用设施的时间),如果他根本没有使用设施,我应该得到null值,并且我应该只获取活动员工记录select employee.empid,employee.empname,employee.status,max(facilities.timestamp as lastusedts)从员工的内部连接设施。
with m as
(
  -- get last timestamp per employee
  select empid
        ,max(timestamp) as lastusedts
    from facilities
    group by e.empid
)
-- report employee info with last timestamp
select e.empid
      ,e.empname
      ,e.status
      ,m.lastusedts
  from employee e
  left join  m 
     on e.empid = m.empid
  where e.status = 'active'