Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate the median of values in SQLite?

Tags:

sqlite

median

I'd like to calculate the median value in a numeric row. How can I do that in SQLite 4?

like image 437
mafu Avatar asked Apr 02 '13 12:04

mafu


People also ask

How do you find the median in SQLite?

2) Create a query that calculates the (max(G.i)+min(G.i))/2.0 for each group (call this column 'x'). 3) Using the Pick table, select entries from G where ABS(G.i-Pick. x)<1 . If you take the average from that last table, you'll have your answer for each group.

How do you find the median of data in SQL?

To get the median we have to use PERCENTILE_CONT(0.5). If you want to define a specific set of rows grouped to get the median, then use the OVER (PARTITION BY) clause. Here I've used PARTITION BY on the column OrderID so as to find the median of unit prices for the order ids.

Does SQL have a median function?

According to MSDN, Median is not available as an aggregate function in Transact-SQL.

How do you find the median in SQL w3schools?

If the total number of observations is an odd number, the formula gives a whole number and the value of this observation is the median. The 4th value in the ordered list is 40, so that is the median. If the total number of observations is an even number, the formula gives a decimal number between two observations.


1 Answers

Let's say that the median is the element in the middle of an ordered list.

SQLite (4 or 3) does not have any built-in function for that, but it's possible to do this by hand:

SELECT x FROM MyTable ORDER BY x LIMIT 1 OFFSET (SELECT COUNT(*)         FROM MyTable) / 2 

When there is an even number of records, it is common to define the median as the average of the two middle records. In this case, the average can be computed like this:

SELECT AVG(x) FROM (SELECT x       FROM MyTable       ORDER BY x       LIMIT 2       OFFSET (SELECT (COUNT(*) - 1) / 2               FROM MyTable)) 

Combining the odd and even cases then results in this:

SELECT AVG(x) FROM (SELECT x       FROM MyTable       ORDER BY x       LIMIT 2 - (SELECT COUNT(*) FROM MyTable) % 2    -- odd 1, even 2       OFFSET (SELECT (COUNT(*) - 1) / 2               FROM MyTable)) 
like image 66
CL. Avatar answered Sep 27 '22 23:09

CL.