How to find median in sql

前端 未结 4 1348
遇见更好的自我
遇见更好的自我 2021-01-24 00:08

I have the following sql query which gives me the total h_time grouped by month, week and day. Instead I want the median h_time for month, week and day. How do I do that in Orac

4条回答
  •  盖世英雄少女心
    2021-01-24 00:35

    The problem isn't the median() function, it's the group by column.

    Oracle DATE datatype is actually a DATETIME, e.g. 2017-05-24 08:09:11. So when comparing dates we have to take the time element into consideration.

    The easiest way to do this is by truncating the date value, which sets the time to midnight. So in your case that would look like this:

    SELECT trunc(day) as DAY,
           MEDIAN(H_TIME) AS H_TIME
    FROM (
        ...
    )
    group by trunc(day)
    

    This solution is better than using to_char() to remove the time element because the datatype remains DATE. So if you sort the results order by trunc(day) you get the expected calendar order, whereas sorting on to_char(day) would give an unexpected alphanumeric ordering.

提交回复
热议问题