【发布时间】:2020-02-19 00:50:45
【问题描述】:
假设我有以下sql数据
species date observations
Bird1 08-09-19 40
Bird1 06-10-19 50
Bird1 11-11-19 60
Bird2 08-09-19 50
Bird2 06-10-19 90
Bird3 06-10-19 10
Bird3 11-11-19 20
并假设我想显示一个月和一种鸟类的观察增量变化(相对于上个月),作为该月鸟类观察总增量的一小部分。给定示例数据,我想要以下结果。
species date observations increment_fraction
Bird1 08-09-19 40 0
Bird1 06-10-19 50 0.2
Bird1 11-11-19 60 0.5
Bird2 08-09-19 50 0
Bird2 06-10-19 90 0.8
Bird3 06-10-19 10 0
Bird3 11-11-19 20 0.5
让我解释一下这些结果。与日期 08-09-19 对应的增量分数为 0,因为没有更早的记录可用。第二行的增量分数为 0.2,因为在日期 08-09-19 和 06-10-19 之间的观察中的总增量是 50,而 Bird1 之间的增量变化08-09-19 和 06-10-19 为 10。增量分数为 10/50 = 0.2。
第三行也是如此:日期06-10-19 和11-11-19 之间的总增量 为20,日期06-10-19 之间的Bird1 增量11-11-19 是 10。增量分数是 10/20 = 0.5。
下面的查询会给我想要的结果:
with increments_table as (
select species, date, observations,
observations - lag(observations, 1, observations) over (partition by species
order by date) as increment
from species_table),
increment_sums as (
select date, sum(increment) as increment_sum
from increments_table
group by date)
select species, date, observations, increment/increment_sum
from increments_table
join increment_sums
on increments_table.date = increment_sums.date
但我想知道这是否可以更紧凑一些。我认为它可以更紧凑,因为它是一个非常基本的操作,但我不确定如何。
问题:有没有办法缩短这个时间?
【问题讨论】: