Search code examples
sqloracle-databasemedian

Calculate median in a SQL query using different tables


I have to calculate (Oracle) the median of the age of some people, but to get the ages I have to search in different tables, so the solutions provided for other questions doesn't help me.

I have 4 tables which I have to join to get the ages of the selected people and then calculate the median.

My query to get the ages is something like:

select p.year_born from patient p
where p.id in (
select distinct md.patient_id
from main_data md, treatment t, patient p, consultation c
where 1 = 1
and t.md_id = md.id 
and md.type = 'SOME_TYPE'
and c.id = p.consultation_id
and md.deleted = 0
and t.deleted = 0
and md.completed = 1
and md.patient_id = p.id
and c.testconsultation = 0);

How could I calculate the median of the years in which the people were born?


Solution

  • try this query:

    WITH 
    t1 as  (SELECT year_born FROM (select TO_NUMBER(p.year_born) year_born from patient p
           where p.id in (
           select distinct md.patient_id
           from main_data md, treatment t, patient p, consultation c
           where 1 = 1
           and t.md_id = md.id 
           and md.type = 'SOME_TYPE'
           and c.id = p.consultation_id
           and md.deleted = 0
           and MLP.deleted = 0
           and md.completed = 1
           and md.patient_id = p.id
           and c.testconsultation = 0)) order by year_born),
    t2 as (SELECT mod(count(year_born),2) as mod_num,count(year_born) as num FROM t1),
    t3 as (SELECT ROWNUM r,t1.* FROM t1),
    t4 as (SELECT CASE WHEN mod_num = 1 then round(num/2) else -1 end as t4_num FROM t2)
    SELECT CASE WHEN t4.t4_num = -1 then ((SELECT year_born FROM t3 where r = (t2.num/2)) +
    (SELECT year_born FROM t3 where r = (t2.num/2) + 1)) / 2 ELSE (SELECT year_born FROM t3 where r = t4_num) end as final_num
    FROM t4,t2;