سؤال

I have a table with several rows per id:

Emp_id  date_checkin  hours
01      2014-05-14     6
01      2014-05-13     6
02      etc.

I want to produce a list of last checkin with the number of emps who last checked in on that date. Ex.

chk_date    
2014-05-14      25
2014-05-13      12
2014-05-11      5

etc.

I'm using a RIGHT JOIN to the table to get the last date for each emp. It looks like:

RIGHT JOIN ( Select   e.emp_id max(e.checkin_date) as chk_date
                 from     empcheckin as e
                 group by chk_date) as T1
       on T1.chk_datee = q.chk_date

This (inner) query does get the last checkin date for each id.

The questions are, what do I query in the main query since I don't need anything from another table? If I query for all the dates, I'm going through thousands of records getting dates that don't even matter. Also, what do I JOIN ON?

هل كانت مفيدة؟

المحلول

I don't really think you need a JOIN, but just some GROUP BYs, like this:

SELECT t.last_date_chckin, COUNT(DISTINCT t.emp_id) AS CountEmp
FROM (
   SELECT emp_id, MAX(checkin_date) AS last_date_checkin
   FROM empcheckin
   GROUP BY emp_id
) AS t
GROUP BY t.last_date_chckin
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top