简体   繁体   中英

Trying to find missing records between two entries

I'm trying to find out missed records between two entries in a second table. I can sort of do it by selecting an ID and working backwards (example later) but need something more dynamic.

My list of 'people':

id |name    |
---|--------|
1  |Seth    |
2  |Richard |
3  |Jacob   |
4  |Kate    |

And corrosponding 'entries' in another table.

id |peopleid |entry_date          |
---|---------|--------------------|
1  |1        |2017-04-12 07:19:44 |
2  |2        |2017-04-12 10:01:44 |
3  |3        |2017-04-12 10:03:00 |
4  |4        |2017-04-12 10:04:00 |
6  |1        |2017-04-13 17:06:00 |
7  |2        |2017-04-13 17:07:00 |
8  |4        |2017-04-13 18:09:00 |
9  |1        |2017-04-13 20:01:00 |
10 |1        |2017-04-13 22:03:00 |
11 |1        |2017-04-14 23:21:00 |

Between Seths first entry at 2017-04-12 07:19 and his second one on 2017-04-13 17 I have a record captured for everyone in the "people" table, so all is well.

But, between Seths entry at 2017-04-13 17:06 and 2017-04-14 08:09 I only have data for Richard(2) and Kate(4) so would need it reported that Jacob's(3) entry is missing.

And between Seth's final swipes (ID's 9, 10, and 11) there was no other peoples data captured and they would need to be reported.

So far I have this for Seths entries between 2017-04-13 17:06 and 2017-04-14 08:09 - To do this I need the end date/record and use the ID to work backwards:

SELECT *
FROM people
WHERE id NOT IN (
SELECT peopleid FROM entries e 
WHERE id >= (
    SELECT id
    FROM entries e
    WHERE id < 9 AND peopleid = 1
    ORDER BY id DESC
    LIMIT 1
) AND id < 9
)

which gives me

id |name  |
---|------|
3  |Jacob |

I was hoping to do an end of week/month query to get break down missing entries by day.

Try something like this. The idea is to first make a cross join connecting every person with every possible date, and thereof select only those rows for which no corresponding entry in the entries -table exists. Hope it works without having to correct to many syntax issues:

select *
from people p join (select distinct date(entry_date) as day from entries) dates
where not exists
  (select * from entries e
   where p.id = e.people_id and dates.day = date(e.entry_date))

Try this and change "?" with the date that you want it to check, (ie 2017-04-13)

SELECT p.* FROM people p 
LEFT JOIN entries e on e.peopleid = p.id AND DATE(entry_date) = ?
WHERE  e.peopleid IS NULL;

SELECT p.* FROM people p 
    LEFT JOIN entries e on e.peopleid = p.id  AND DATE(entry_date) = '2017-04-13'
    WHERE  e.peopleid IS NULL;

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