Search code examples
mysqlsqlmedian

MySQL - Including the results of a procedure in a select statement


I have a table, called gcrunarrays with the columns {run_id, time_id, co2}. I have several thousand runs with distinct run_id's, each with 58 time-dependent values for co2. I have a procedure to obtain the median co2 of all runs at a given time. Now, I need a select statement that will obtain the medians for each time. So far, I have

select DISTINCT A.time_id, M.co2 from gcrunarrays A, call getMedian(1, A.time_id) M
GO

Which gets a syntax error. I am fairly new at SQL and I'm working in MYSQL. I've tried about a dozen different ways of wording this statement but now I'm at the point where I feel like I've done something inherently wrong. I think it might work better if median were a function but I'm not sure even how to get the median without using a select statement. Any suggestions are greatly appreciated.

For greater clarification:

Table gcrunarrays

run_id | time_id | co2
1      | 1       | 
1      | 2       | 
...
1      | 58      | 
2      | 1       | 
...    
2      | 58      | 
3 ...

Median Procedure

CREATE PROCEDURE getMedian (IN e INT, t INT)
BEGIN
SELECT count(*), x.co2
FROM (SELECT B.exp_id, A.* FROM gcRunArrays A JOIN gcRuns B ON A.run_id=B.run_id WHERE B.exp_id=e and A.time_id=t) x, 
     (SELECT B.exp_id, A.* FROM gcRunArrays A JOIN gcRuns B ON A.run_id=B.run_id WHERE B.exp_id=e and A.time_id=t) y
GROUP BY x.co2
HAVING SUM(SIGN(1-SIGN(y.co2-x.co2))) = CEILING((COUNT(*)+1)/2);
END
GO

Solution

  • Use a temp table can easily solve the issue. And it is not possible to use procedure results as table directly.

    Can a stored procedure/function return a table?