mardi 23 décembre 2014

Sqlite: select, grouping according to one attribute desc. and sorting according to another asc

What is the best way to group according to an attribute in descending order, but sort according to another in ascending order.



CREATE TABLE IF NOT EXISTS
logs (id INTEGER NOT NULL,
prompt INTEGER NOT NULL,
value TEXT,
PRIMARY KEY (id));

INSERT INTO logs(id, prompt, value) VALUES(1, 10, "a");
INSERT INTO logs(id, prompt, value) VALUES(2, 4, "a");
INSERT INTO logs(id, prompt, value) VALUES(3, 10, "b");
INSERT INTO logs(id, prompt, value) VALUES(4, 6, "c");
INSERT INTO logs(id, prompt, value) VALUES(5, 5, "c");
INSERT INTO logs(id, prompt, value) VALUES(6, 4, "d");
INSERT INTO logs(id, prompt, value) VALUES(7, 4, "e");
INSERT INTO logs(id, prompt, value) VALUES(8, 10, "a");
INSERT INTO logs(id, prompt, value) VALUES(9, 10, "z");


Now, I would like a request that is going to:




  1. group according to prompt (only one row per distinct prompt)




  2. keep only the value of the row with largest id




  3. sort by ascending id (which I don't need to keep)




So for here I need



prompt | value
10 | "z"
4 | "e"
6 | "c"
5 | "c"


How is this possible? And how it can be made not too inefficient? And can you avoid an intermediate request (i.e., select from a select - which I feel might the way to do it, but not sure how).


Aucun commentaire:

Enregistrer un commentaire