I have a table with app statistics, let’s say the columns are os_version and app_id (simplifying). I want to list all OS versions for a certain app, and for each OS version I want to see a number of records that have at least this OS version. Example data:
app1 1.0
app1 2.0
app2 1.0
Now for app1 I want to see:
version | score | comments
--------+-------+---------
1.0 | 2 | there are two records having OS at least 1.0
2.0 | 1 | there is just one record with OS at least 2.0
Now, pardon my ignorant SQL, but I have come up with this query:
SELECT
os_version,
-- number_of_records_having_at_least_this_version / number_of_all_records
(SELECT COUNT(*) FROM stats WHERE app_id='app1' AND os_version >= outer.os_version)/
(SELECT COUNT(*) FROM stats WHERE app_id='app1') AS score
FROM (SELECT * FROM stats WHERE app_id='app1') AS outer
GROUP BY os_version;
This is crazy, as I have to filter by the app ID three times. Is it possible to filter by the app ID first and then use the resulting row set for further operations? Without a temporary table? In SQLite? Something like:
SELECT
os_version,
(SELECT COUNT(*) FROM filtered WHERE os_version >= filtered.os_version)/
(SELECT COUNT(*) FROM filtered) AS score
FROM (SELECT * FROM stats WHERE app_id='app1') AS filtered
GROUP BY os_version;
…which, sadly, does not work.
I think, if I’ve understood the question properly, that something like this should do the trick..
EDIT: This returns results fitered by app_id (as with the example query in the question)
EDIT2:
EDIT3: To get round the 2.11 < 2.7 problem