Got a problem with a query I’m trying to write. I have a table that lists people that have been sent an email. There is a bit column named Active which is set to true if they have responded. But I need to count the number of consecutive emails the person has been inactive since either their first email or last active email.
For example, this basic table shows one person has been sent 9 emails. They have been active within two of the emails (3 & 5). So their inactive count would be 4 as we are counting from email number 6 onwards.
PersonID(int) EmailID(int) EmailDate(datetime) Active(bit)
1 1 2009-07-18 19:56:20 0
1 2 2009-08-18 19:56:20 0
1 3 2009-09-18 19:56:20 1
1 4 2009-10-18 19:56:20 0
1 5 2009-11-18 19:56:20 1
1 6 2009-12-18 19:56:20 0
1 7 2010-01-18 19:56:20 0
1 8 2010-02-18 19:56:20 0
1 9 2010-03-18 19:56:20 0
Any pointers or help would be great.
Regards
Greg
My first cut:
Note that this solution requires that each person answers at least one email. If you want to include people who were inactive from the very first email that was sent to them you need to wrap that (MAX(EmailDate)) term inside some kind of IFNULL() returning a date before the start date of the system for NULLs.
Also, as KM points out below, if someone is not currently inactive (they answered the most recent email) they will not be in the result set. I think that probably meets your needs but, if not, let me know.