开发者

Determine 'valid until' date in MySQL query

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 wan开发者_如何学编程t 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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜