Skip to content
Advertisement

How to run a query to get results of last 12 months ( BigQuery)

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?

Advertisement

Answer

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() 
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement