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

时间:2015-06-05 07:03:12

标签: sql join db2 max left-join

我有一张员工表

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

我有另一个名为facility

的表
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

所以我必须加入我的员工表和设施表,并通过获取最大时间戳来查找员工上次使用设施的时间,对于未使用它的员工,时间戳值应为空,只有活跃员工被拿走了。 请帮我在db2中编写这个查询

5 个答案:

答案 0 :(得分:2)

使用LEFT JOIN执行GROUP BY查找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 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'

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:0)

 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 

答案 3 :(得分:0)

公用表格式[CTE' s]是将问题分解为更容易的块的一种方法。

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'

答案 4 :(得分:0)

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