I have read that it is possible to implement anything you might do in a SQL window function, with creative use of joins, etc, but I cannot figure out how. I'm using SQLite in this project, which doesn't currently have window functions.
I have a table with four columns:
CREATE TABLE foo (
id INTEGER PRIMARY KEY,
x REAL NOT NULL,
y REAL NOT NULL,
val REAL NOT NULL,
UNIQUE(x,y));
and a convenience function DIST(x1, y1, x2, y2) that returns the distance between two points.
What I want: For every row in that table, I want the entire row in that same table within a certain distance [eg 25 km], with the lowest "val". For rows with the same "val", I want to use lowest distance as a tie breaker.
My current solution is running n+1 queries, which works but is ucky:
SELECT * FROM foo;
... then, for each row returned, I run [where "src" is the row I just got]:
SELECT * FROM foo
WHERE DIST(foo.x, foo.y, src.x, src.y)<25
ORDER BY val ASC, DIST(foo.x, foo.y, src.x, src.y) ASC
LIMIT 1
But I really want it in a single query, partially for my own interest, and partially because it makes it much easier to work with some other tools I have.
Aucun commentaire:
Enregistrer un commentaire