加入 2 tables 并从第一个 table 获取一些列,从第二个 table 获取最大时间戳值

join 2 tables and get some columns from 1st table and max timestamp value from second table

我有员工table

empid empname status
1     raj     active
2     ravi    active
3     ramu    active
4     dan     active
5     sam     inactive

我有另一个 table 设施

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

所以我必须加入我的员工 table 和设施 table 并通过获取时间戳的最大值来查找员工最后一次使用设施的时间,对于没有使用它的员工timestamp 值应该为 null,并且只获取活跃的员工。 请帮助我在 db2

中编写此查询

试试这个

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

使用 GROUP BY 执行 LEFT JOIN 以找到 MAX(时间戳):

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:

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'
 SELECT e.empid, e.empname, e.status, MAX(f.timestamp) AS lastusedts 
 FROM employee e LEFT OUTER JOIN facilities f ON e.empid = f.empid 
 WHERE e.status = 'active' GROUP BY e.empid, e.empname, e.status 

常用 table 表达式 [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'

常用 table 表达式 [CTE's] 是一种将问题分解为更简单的块的方法。

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'