How to find median in sql

前端 未结 4 1349
遇见更好的自我
遇见更好的自我 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.

    0 讨论(0)
  • 2021-01-24 00:37

    Your problem probably come from the time part that the DATE type carry (even if you don't explicitly set it).

    To get rid of it you can use the trunc function.

    Replace:

    SELECT DAY,
    

    By:

    SELECT trunc(DAY)
    

    And:

    GROUP BY DAY
    

    By:

    GROUP BY trunc(DAY)
    
    0 讨论(0)
  • 2021-01-24 00:42

    Try to use to_char(DAY) in group by and select statement

    0 讨论(0)
  • 2021-01-24 00:58

    Try replacing :

    SUM(H_TIME) AS HANDLE_TIME
    

    by :

    MEDIAN(H_TIME) AS HANDLE_TIME
    

    (line 3)


    EDIT: For the months, replace:

    select 
    MONTH, WEEK, DAY,
    

    By:

    select 
    MONTH,
    

    And:

    GROUP BY
    
    MONTH
    ,WEEK
    ,DAY
    

    By:

    GROUP BY 
    MONTH
    


    For the weeks, replace:

    select 
    MONTH, WEEK, DAY,
    

    By:

    select 
    MONTH, WEEK,
    

    And:

    GROUP BY
    
    MONTH
    ,WEEK
    ,DAY
    

    By:

    GROUP BY 
    MONTH
    ,WEEK
    
    0 讨论(0)
提交回复
热议问题