简体   繁体   中英

How to join tables with aggregate functions in MYSQL query?

I have two tables from the database and I want to get the last status of each id. Tried adding the INNER JOIN claus but no avail. These are what my data looks like:

Table: employee

id   name   department
-------------------------
1    A       X
2    B       Y
3    C       Z

Table: timelog

id   time       status    count
-------------------------------
1    08:51       IN       1
3    09:00       OUT      2
2    09:00       IN       3
2    18:00       OUT      4
1    18:05       OUT      5

Currently, this is the query that I use but need to get the name of each employee.

SELECT 
     *
FROM timelog
WHERE timelog.count
IN   (SELECT MAX(timelog.count)
      FROM timelog
      GROUP BY timelog.id) 
ORDER BY clock.id;

Current output:

id   time       status
-------------------------------
1    18:05      OUT
2    18:00      OUT
3    09:00      OUT

This is the output I want to achieve:

id   name      time       status
-------------------------------
1    A         18:05      OUT
2    B         18:00      OUT
3    C         09:00      OUT

Is it possible to add JOIN to the above query? If no, what would be the workaround? Any help would be greatly appreciated. TIA.

You can join the tables and use a correlated subquery for filtering:

select 
    e.id,
    e.name,
    t.time,
    t.status
from employee e
inner join timelog t on t.id = e.id
where t.count = (
    select max(count)
    from timelog t1
    where t1.id = t.id
)

Use a correlated subquery to get the last record for each id in timelog :

SELECT e.*, tl.*
FROM employee e JOIN
     timelog tl
     ON e.id = tl.id
WHERE tl.count = (SELECT MAX(tl2.count)
                  FROM timelog tl2
                  WHERE tl2.id = tl.id
                 ) ;

Note that your version of the query is not correct. The subquery returns the maximum count for each id. However, the outer query might match a different id to the count in the subquery. The correlation clause fixes this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM