获得重叠时间范围的中位数

时间:2016-07-15 00:34:31

标签: sql vertica

例如,

vertica db有一个名为revenue的表:

date             revenue
2016-07-12          1
2016-07-12          10
2016-07-12          5
2016-07-12          3
2016-07-13          7
2016-07-13          120
2016-07-13          22
2016-07-14          5
2016-07-14          17

棘手的是我不希望每个日期的中位数,但我想计算每天给出的时间范围> =的中位数收入,例如结果如下:

daterange       median_revenue
>= 2016-07-12         7
>= 2016-07-13         17
>= 2016-07-14         11

要明确:

7 = median(1,10,5,3,7,120,22,5,17)
17 = median(7,120,22,5,17)
11 = median(5,17)

我怎么能为这些日期范围编写sql脚本?有一种简单的查询方式吗?我不想在每个日期范围内计算然后联合,因为有很多天。

2 个答案:

答案 0 :(得分:2)

这会有帮助吗?

SELECT
    date_table.[date],
    MEDIAN (r.revenue) AS median_revenue
FROM 
    (SELECT DISTINCT [date] FROM revenue) date_table
LEFT JOIN revenue r ON r.[date] >= r_main.[date]
GROUP BY
    date_table.[date]

答案 1 :(得分:1)

刚想通了

select distinct date, median(revenue) over (partition by date) as rev_median  
from (select a.date,b.revenue 
      from (select distinct date from revenue_test) a 
      left outer join revenue b 
           on a.date<=b.date order by a.date,b.date) a ;`