How to show incremental changes in SQL

妖精的绣舞 提交于 2021-01-28 02:22:11

问题


I have a sql (Presto) table that contains data about different kinds of bird species. The table contains information about how often the different species have been observed in a park over different months. Some of the species have not been observed in certain months, but measurements were only performed on 07-9-19, 08-10-19, and 05-11-19. A sample of the data would look like this

Species        Period     Total (Cumulative) Observations (TCO)

Bird1           07-9-19            33
Bird1           08-10-19           45
Bird1           05-11-19           60
Bird2           07-9-10            20
Bird3            ....            ....
Bird3            ....            ....
....             ....            ....

What I would like is to add a new column to this table that captures incremental change between two days of measurement for each species. Based on the example sample I would like to produce the following result:

Species        Period            TCO        Change

Bird1           07-9-19            33          33
Bird1           08-10-19           45          12
Bird1           05-11-19           60          15
Bird2           07-9-10            20          20
Bird3           08-10-19           5           5
Bird3           05-11-19           24          19
....             ....            ....

I think I've found a way to do this, but it is quite complicated and involves creating a new table. I was wondering if there was are simpler solution to my problem (as it is slightly simpler than the problem in the link).


回答1:


You can use window function lag() to recover the previous tco for the same species, period-wise:

select 
    t.*,
    tco - lag(tco, 1, 0) over(partition by species order by period) change
from mytable

The three-argument form of lag lets you specify a default value instead of null: as per your expected result, you want 0 in that case.



来源:https://stackoverflow.com/questions/58493773/how-to-show-incremental-changes-in-sql

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