在MySQL中使用First_Value函数时值错误

时间:2019-06-20 13:58:41

标签: mysql function partition

我需要根据此表准备一份报告,我只能阅读:

enter image description here

这个想法是基于更高的活动识别度,为每个观察值取最后一个值。例如,观察值10的值对应于活动编号19。

enter image description here

到目前为止,这是我的代码:

select 
first_value(text) over (partition by employee order by case when observation = 10 then activity else 0 end desc) as "Obs 10",
first_value(number) over (partition by employee order by case when observation = 20 then activity else 0 end desc) as "Obs 20",
first_value(dropdown) over (partition by employee order by case when observation = 40 then activity else 0 end desc) as "Obs 40"
-- the same for the rest of the observations
from employee_proc

但是,员工可以与执行查询时尚未注册的其他观察相关联。

如果我为此员工提供了这段代码:

...
first_value(text) over (partition by employee order by case when observation = 120 then activity else 0 end desc) as "Obs 120",
...

我得到的是错误的值而不是null(假设观察值尚未为他注册)。

如何避免得到这种结果?是否有另一种方式来获得最终结果,而另一种方式是经过优化的?

致谢。

1 个答案:

答案 0 :(得分:1)

通过以下查询,可以更有效地实现问题中显示的结果:

ls