Reputation: 111
I want to get records for last 12 months for a particular ID in Big Query table. I have extracted month and year as separate columns from the original timestamp column. I tried using date_add() and date_diff() but i am getting some errors. My Dataset is like:
Month Year MonthName ID
8 2018 August 1
9 2018 September 2
9 2017 September 3
How can i achieve this?
Upvotes: 6
Views: 24455
Reputation: 1
If you're looking for the last 12 full-months:
SELECT
DATE_SUB((DATE_TRUNC(CURRENT_DATE(), month)), INTERVAL 1 month),
DATE_SUB((DATE_TRUNC(CURRENT_DATE(), month)), INTERVAL 13 month)
Upvotes: 0
Reputation: 173190
I have extracted month and year as separate columns from the original timestamp column
I recommend doing 12 months filtering based on your original timestamp column.
Assuming it is named ts
- below is for BigQuery Standard SQL
WHERE DATE(ts) BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 12 MONTH) AND CURRENT_DATE()
for example
#standardSQL
SELECT ts, id
FROM `project.dataset.table`
WHERE id = 1
AND DATE(ts) BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 12 MONTH) AND CURRENT_DATE()
Upvotes: 16
Reputation: 1
timestamp
is assumed as standard timestamp naming for your BQ table as time identifier field. So you can filter like below to get last 12 month data only:
WHERE DATE(TIMESTAMP_MILLIS(timestamp)) BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 12 MONTH) and CURRENT_DATE()
Upvotes: 0
Reputation: 1271003
One method is to convert the year/month into months since some date. Then do the same with the current date:
where year * 12 + month >= extract(year from current_date) * 12 + extract(month from current_date) - 12
This assumes you have no future data. The same idea holds for future dates (using < rather than >=).
Upvotes: 0