如果最后一条记录与之前的记录重复,则android-db查询获取最后一条记录或组中的第一条

andorid-db query to get last records or first of the group if the last record is duplicate of previous

有一个 table status 包含如下所示的数据:

Id    Status     TimeStamp
-------------------------
1    StatusC     1234561
2    StatusC     1234562
3    StatusB     1234563
4    StatusA     1234564
5    StatusA     1234565
6    StatusA     1234566

什么查询会return下面的结果?

Id    Status     TimeStamp
-------------------------
4    StatusA     1234564

另一个例子:

Id    Status     TimeStamp
-------------------------
1    StatusC     1234561
2    StatusC     1234562
3    StatusB     1234563
4    StatusA     1234564
5    StatusA     1234565
6    StatusB     1234566

结果:

Id    Status     TimeStamp
-------------------------
6    StatusB     1234566

所以我想要最后一个状态记录,如果它与前一个不同,或者如果前一个和最后一个状态相同,那么我想要那个组中的第一个。我尝试了几件事,但没有得到所需的结果。有什么有效的方法可以达到这个效果吗?

您想要与最新(最高时间戳)行具有相同状态的最早(最低时间戳)记录(行),但它后面没有另一行具有不同的状态。

试试这个:

 Select *
 from table p
 where p.Timestamp = 
     (Select min(TimeStamp) from table x
      where status = 
           (Select Status from table 
            Where timestamp = 
               (Select Max(timestamp) From table))
          and not exists 
                 (Select * from table
                  Where timestamp > x.timeStamp
                      and status != p.Status))