Search code examples
sqlmariadbmedian

MariaDB messes up median when using agregate function


I've noticed that MariaDB messes up the median calculation if you try to get the median and an aggregate function on same query

I created a simple example test my theory

CREATE TABLE `test` (
  `a` int(11) DEFAULT NULL, 
  `pk` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


INSERT INTO `test` (`a`,  `pk`) VALUES
(1,  18),
(2,  19),
(3,   20),
(2,   21);

so anyone with basic statistics notion would conclude that

median a = 2

and these are the results if i do

SELECT
    median(a) over (),
FROM
    test;

HOWEVER

if i try to get the median together with any aggregate function, the result is always one

so, for example:

SELECT
sum(a),
    median(a) over ()   
  
FROM
    test;

the result will be: 8 1

this will happen to any aggregate function, sum, max, min, avg...

and the result is always one...

is there an explanation for that? is there a way to get this working in 1 query?


Solution

  • You need to use SUM() in a window function as well.

    SELECT
        SUM(a) OVER (),
        MEDIAN(a) OVER ()   
    FROM
        test
    LIMIT 1;
    

    Since you aren't partitioning in the window, you'll get a result for every row in the table. I've added LIMIT 1 to prevent all this duplication.