Skip to content
Advertisement

How to retrieve last year data on line-by-line basis (main set grouped by year, month & aggregated on volume)?

Is there a way to easily retrieve last years data during volume aggregation, grouped by year, month.

Sample of code below (from BQ). It shows an error in the subquery WHERE clause expression references t1.date which is neither grouped nor aggregated

Advertisement

Answer

If you have data every month, then you can use lag(). I would recommend using date_trunc() instead of separating the year and date components. So:

If you have missing months for some products, then you can still use window functions, but the logic is a bit more complicated.

EDIT:

If you don’t have data every month, then you can use a RANGE specification, but you need a month counter:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement