Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
Lag window function in SQLite#
Here’s how to use a lag window function to calculate new cases per day when the table just has total cases over time on different dates.
The key clause is this:
1select2 day,3 confirmed - lag(confirmed, 1) OVER (4 ORDER BY5 day6 ) as new_casesSo the syntax is lag(column, 1) over (order by day) - to get the previous value of column based on the day.
Full example query (using a CTE as well):
1with italy as (2 select3 rowid,4 day,5 country_or_region,6 province_or_state,7 admin2,8 fips,9 confirmed,10 deaths,11 recovered,12 active,13 latitude,14 longitude,15 last_update,16 combined_key17 from18 johns_hopkins_csse_daily_reports19 where20 "country_or_region" = :p021 order by22 confirmed desc23)24select25 day,26 confirmed - lag(confirmed, 1) OVER (27 ORDER BY28 day29 ) as new_cases30from31 italy32order by day desc limit 50Originally tweeted here: https://twitter.com/simonw/status/1246482954630492200
Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.