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

1.4k views Asked by At

I have a employee table

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

I have another table called facilities

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

I want my result like

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

So i have to join my employee table and facilities table and find when the employee has last used the facilities by getting the max of time stamp and for employees who did not use it the timestamp value should be null and only active employees are to be fetched. Please help me in writing this query in db2

5

There are 5 answers

0
jarlh On BEST ANSWER

Do a LEFT JOIN with a GROUP BY to find the MAX(timestamp):

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

Alternatively, a correlated sub-select for the max-timestamp:

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'
2
Zohaib Waqar On

try this

SELECT employee.empid, employee.empname, employee.status,facilities.timestamp as lastusedts
FROM employee
INNER JOIN facilities
ON employee.empid=facilities.empid;
1
Yathish Manjunath On
 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 
0
WarrenT On

Common table expressions [CTE's] are one way you can break a problem down into easier chunks.

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'
0
WarrenT On

Common table expressions [CTE's] are one way you can break a problem down into easier chunks.

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'