Comparing “Consecutive” Rows in Ms Access

只谈情不闲聊 提交于 2019-12-08 13:11:32

How about:

SELECT t2.*
FROM (SELECT t.ID, t.Subid, t.Time, t.Value, t.Value2
FROM Test2 t
WHERE t.Time=4)  AS t2 LEFT JOIN (SELECT t.ID, t.Subid, t.Time, t.Value, t.Value2
FROM Test2 t
WHERE t.Time=3)  AS t1 ON t2.ID = t1.ID
WHERE t2.Value<>t1.Value 
OR t2.Value2<>t1.Value2 
OR t1.ID Is Null
UNION ALL
SELECT t1.* FROM
(SELECT t.ID, t.Subid, t.Time, t.Value, t.Value2
FROM Test2 t
WHERE t.Time=3) t1
LEFT JOIN
(SELECT t.ID, t.Subid, t.Time, t.Value, t.Value2
FROM Test2 t
WHERE t.Time=4) t2
ON t1.ID=t2.ID
WHERE t1.Value <> t2.Value
OR  t1.Value2 <> t2.Value2
OR t2.ID Is Null
ORDER BY ID

Since this is MS Access, how about creating a query with two copies of t (Access calls the second t_1) (just connect every field, or look at this http://i49.tinypic.com/rix175.jpg.)

Then right-click, edit SQL, and you should see something like this:

    SELECT t.ID, t.Subid, t.Time, t.Value, t.Value2
    FROM t INNER JOIN t AS t_1 ON (t.Value2 = t_1.Value2) 
    AND (t.Value = t_1.Value) 
    AND (t.Subid = t_1.Subid) 
    AND (t.Time = t_1.Time-1) 
    AND (t.ID = t_1.ID);

Which you can re-write like this:

    SELECT t.ID, t.Subid, t.Time, t.Value, t.Value2
    FROM t INNER JOIN t AS t_1 ON 
    (t.Time = t_1.Time-1)
    AND (t.ID = t_1.ID) 
    AND (t.Subid = t_1.Subid) 
    AND ((t.Value <> t_1.Value) OR (t.Value2 <> t_1.Value2));

Note the "t.Time = t_1.Time-1" edit, and the AND statement; this will give you the query results from Time = 3. Now do a UNION on this, slightly modified, this time with "t.Time-1 = t_1.Time" instead to get the Time = 4 results. Then add one at the end to catch the unique entries:

    SELECT t.ID, t.Subid, t.Time, t.Value, t.Value2
    FROM t INNER JOIN t AS t_1 ON 
    (t.Time = t_1.Time-1) 
    AND (t.ID = t_1.ID) 
    AND (t.Subid = t_1.Subid) 
    AND ((t.Value <> t_1.Value) OR (t.Value2 <> t_1.Value2))

    UNION SELECT t.ID, t.Subid, t.Time, t.Value, t.Value2
    FROM t INNER JOIN t AS t_1 ON 
    (t.Time-1 = t_1.Time)  
    AND (t.ID = t_1.ID)
    AND (t.Subid = t_1.Subid) 
    AND ((t.Value <> t_1.Value) OR (t.Value2 <> t_1.Value2))

    UNION SELECT t.ID, t.Subid, t.Time, t.Value, t.Value2
    FROM t INNER JOIN t AS t_1 ON 
    (t.Time-1 = t_1.Time) 
    AND (t.ID <> t_1.ID) 
    AND (t.Subid <> t_1.Subid);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!