mercredi 24 février 2016

SQL (sqlite) Query Loop [duplicate]

This question already has an answer here:

We have a table accidents with the following structure:

create table accidents {
    id integer not null,
    type integer not null,
    value integer not null,
    time timestamp unique not null,
};

Now, we need an SQL query that, for each id and type (id, type), returns the most recent value (in terms of time).

For example, given the following data:

| id        | type       | value | time                |
|-----------|------------|-------|---------------------|
| 2         | 2          | 10    | 2014-02-13 12:42:00 |
| 2         | 4          | 45    | 2014-02-13 13:19:57 |
| 2         | 2          | 22    | 2014-02-13 14:48:30 |
| 3         | 2          | 71    | 2014-02-13 12:54:39 |
| 2         | 3          | 53    | 2014-02-13 13:32:36 |

The query should return the following results (we order by id and type):

| id        | type       | value |
|-----------|------------|-------|
| 2         | 2          | 22    |
| 2         | 3          | 53    |
| 2         | 4          | 45    |
| 3         | 2          | 71    |

So far:

SELECT id, type, value
FROM accidents
WHERE (
     --- LOOP HERE
)
ORDER BY id ASC, type ASC;

Problem:

We can see that we need to go for each id: then for each type compare the time. However, We can not figure out how to do that loops, and even so remove (or transfer to a new table) the selected records on runtime.

Thank you all for your help and support.

Aucun commentaire:

Enregistrer un commentaire