How to find median in sql

喜你入骨 提交于 2019-12-20 05:22:09

问题


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 Oracle SQL?

 SELECT DAY,

MEDIAN(H_TIME) AS HANDLE_TIME

FROM(
    select 
MONTH, WEEK, DAY,

    CASE 
        WHEN C.JOINED IS NOT NULL
            THEN (NVL(C.TOTAL_TALK,0) + NVL(C.TOTAL_HOLD,0) + (NVL((C.DATETIME - C.START_DATETIME)*86400,0)) )/86400 
            ELSE 0 END AS H_TIME

from TABLE1 C


LEFT JOIN TABLE2 S
ON S.ID = C.ID
where c.direct = 'Inbound'
)

where UPPER(ITEM1) like 'SOMETHING%' 

GROUP BY


DAY

OUTPUT:

DAY              HANDLE_TIME
14-APR-17   .00567129629629629629629629629629629629629
15-APR-17   0
17-APR-17   0
17-APR-17   .00422453703703703703703703703703703703703
19-APR-17   .00269675925925925925925925925925925925925
19-APR-17   0
19-APR-17   0
19-APR-17   .00824074074074074074074074074074074074074

回答1:


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)



回答2:


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



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/44118860/how-to-find-median-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!