I want to compute Median from y in the subgroups of this simple xy_table :
x | y --groups--> gid | x | y --medians--> gid | x | y ------- ------------- ------------- 0.1 | 4 0.0 | 0.1 | 4 0.0 | 0.1 | 4 0.2 | 3 0.0 | 0.2 | 3 | | 0.7 | 5 1.0 | 0.7 | 5 1.0 | 0.7 | 5 1.5 | 1 2.0 | 1.5 | 1 | | 1.9 | 6 2.0 | 1.9 | 6 | | 2.1 | 5 2.0 | 2.1 | 5 2.0 | 2.1 | 5 2.7 | 1 3.0 | 2.7 | 1 3.0 | 2.7 | 1
In this example, each x is unique and the table is already sorted by x . Now I want GROUP BY round(x) and get a tuple that contains the median y in each group.
I can already calculate the median for the entire table with this ranking query :
SELECT ax, ay FROM xy_table a,xy_table b WHERE ay >= by GROUP BY ax, ay HAVING count(*) = (SELECT round((count(*)+1)/2) FROM xy_table)
Output: 0.1, 4.0
But I have not yet managed to write a query to calculate the median for subgroups.
Note: I do not have the median() aggregation function. Also, do not offer solutions with the special PARTITION , RANK or QUANTILE (as in similar questions, but too specific for the provider, https://stackoverflow.com/a/4649/ ). I need plain SQL (i.e. SQLite compatible without median() function)
Edit: I was really looking for Medoid , not Median .
sql sqlite group-by median ranking
Juve
source share