views:

41

answers:

1

In this table I store changeable values for certain spids. As days go by, these values can change, and an spid can get a new value.

Now I want to find out until when a certain value is enabled.

This is the data for a single spids

uid  spid   propertyvalue   creationdate      
--------------------------------------------------
1    3      First name       2010-01-17 22:34:00
37   3      Second name      2010-01-18 01:07:24
38   3      Third name       2010-01-18 01:09:00
39   3      Fourth name      2010-01-18 01:18:16
40   3      Fifth name       2010-01-18 01:20:02

So the first value starts at 2010-01-18 01:07:24 and would be valid until 2010-01-18 01:01:00.

I already tried this query:

SELECT s1 . * , 
       s2.creationdate AS datetwo
  FROM salespointproperty s1
  JOIN salespointproperty s2 ON s1.spid = s2.spid
                            AND s1.creationdate < s2.creationdate

That gives me a lot of double-records (some of them wrong), and it always leaves out the last new name (as it doesn't have a new creationdate following it) Example:

uid spid    propertyvalue    creationdate           datetwo
-------------------------------------------------------------- 
1   3       First name       2010-01-17 22:34:00    2010-01-18 01:07:24 *
1   3       First name       2010-01-17 22:34:00    2010-01-18 01:09:00
37  3       Second name      2010-01-18 01:07:24    2010-01-18 01:09:00 *
1   3       First name       2010-01-17 22:34:00    2010-01-18 01:18:16
37  3       Second name      2010-01-18 01:07:24    2010-01-18 01:18:16
38  3       Third name       2010-01-18 01:09:00    2010-01-18 01:18:16 *
1   3       First name       2010-01-17 22:34:00    2010-01-18 01:20:02
37  3       Second name      2010-01-18 01:07:24    2010-01-18 01:20:02
38  3       Third name       2010-01-18 01:09:00    2010-01-18 01:20:02
39  3       Fourth name      2010-01-18 01:18:16    2010-01-18 01:20:02 *

Only the lines with an asterix are correct. The fifth name is missing.

+1  A: 

Assuming that in your example, uid 37 is valid until uid 38, uid 38 is valid until uid 39 etc.

SELECT
  s1.uid,
  s1.spid,
  s1.propertyvalue,
  s1.creationdate,
  MIN(s2.creationdate) AS datetwo
FROM salespointproperty s1
INNER JOIN salespointproperty s2
    ON s1.spid = s2.spid
    AND s1.creationdate < s2.creationdate
GROUP BY
  s1.uid,
  s1.spid,
  s1.propertyvalue,
  s1.creationdate;
lins314159
Thank you, that does list only the correct dates. Perfect.But how do I get the fifht date to appear? (The date which does not have an end date. Or it should be NOW())
skerit
Change INNER JOIN to LEFT JOIN, change datetwo to `COALESCE(MIN(s2.creationdate), NOW())`.
lins314159
Brilliant, thank you.
skerit