How to get Last record from Sqlite?

前端 未结 12 2072
悲&欢浪女
悲&欢浪女 2020-12-02 07:37

I have a one table question_table and one ImageButton (Back). I need to get the last inserted record from the database after clicking on t

12条回答
  •  执笔经年
    2020-12-02 08:31

    Another option is to use SQLites LAST_VALUE() function in the following way.

    Given this table:

    +--------+---------+-------+
    | OBJECT |  STATUS |  TIME |
    +--------+---------+-------+
    |        |         |       |
    | 1      |  ON     |  100  |
    |        |         |       |
    | 1      |  OFF    |  102  |
    |        |         |       |
    | 1      |  ON     |  103  |
    |        |         |       |
    | 2      |  ON     |  101  |
    |        |         |       |
    | 2      |  OFF    |  102  |
    |        |         |       |
    | 2      |  ON     |  103  |
    |        |         |       |
    | 3      |  OFF    |  102  |
    |        |         |       |
    | 3      |  ON     |  103  |
    +--------+---------+-------+
    

    You can get the last status of every object with the following query

    SELECT                           
        DISTINCT OBJECT,             -- Only unique rows
        LAST_VALUE(STATUS) OVER (    -- The last value of the status column
            PARTITION BY OBJECT      -- Taking into account rows with the same value in the object column
            ORDER by time asc        -- "Last" when sorting the rows of every object by the time column in ascending order
            RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING    -- Take all rows in the patition
        ) as lastStatus
    FROM
        TABLE
    

    The result would look like:

    +--------+--------------+
    | OBJECT |  LAST_STATUS |
    +--------+--------------+
    |        |              |
    | 1      |  ON          |
    |        |              |
    | 2      |  ON          |
    |        |              |
    | 3      |  ON          |
    +--------+--------------+
    

提交回复
热议问题