我有一个表,每个客户每天存储一次最新的指标。简化的模式看起来大致如此,让我们调用这个表历史::
bus_date | client_id | ytd_costs
我希望创建一个视图,添加一个星期至今的成本,基本上是在周五之前发生的任何成本被视为本周迄今的一部分。目前,我有以下内容,但我关注的是切换案例逻辑。
以下是我现在的逻辑示例,表明这是有效的。 我还得使用之前从未使用的时间条款......
;with history as (
select bus_date,client_id,ts_first_Value(value,'linear') "ytd_costs"
from (select {ts'2016-10-07'} t,1 client_id,5.0 "value" union all select {ts'2016-10-14'},1, 15) k
timeseries bus_Date as '1 day' over (partition by client_id order by t)
)
,history_with_wtd as (select bus_date
,client_id
,ytd_costs
,ytd_costs - decode(
dayofweek(bus_date)
,6,first_value(ytd_costs) over (partition by client_id order by bus_date range '1 week' preceding)
,first_value(ytd_costs) over (partition by client_id,date_trunc('week',bus_date+3) order by bus_date)
) as "wtd_costs"
,ytd_costs - 5 "expected_wtd"
from history)
select *
from history_with_wtd
where date_trunc('week',bus_date) = '2016-10-10'
在Sql server中,我可以使用lag函数,因为我可以将变量传递给look-back子句。但在Vertica中没有这样的选择。
答案 0 :(得分:0)
星期六从星期开始分区怎么样?首先抓住一周的第一天,然后在周六开始抵消。 trunc(bus_date + 1,'D') - 1
另请注意窗口框架是从分区的开头(星期六,unbounded preceding
)到current row
。
select
bus_date
,client_id
,ytd_costs
,ytd_costs - first_value(ytd_costs) over (
partition by client_id, trunc(bus_date + 1,'D') - 1
order by bus_date
range between unbounded preceding and current row) wtd_costs
from sos.history
order by client_id, bus_date