I've differents queries at Bigquery but only need run one time for month (with all close data from the last month). At the moment i change the dates manually at the query but i need change this and make a function that give me the data from the last past.
For exemple: I run this queries the 1st or 2nd day of July, and need that the query takes the data from 1st to 30th of June. (The query is write in Standard SQL Dialect)
Thanks.
Code:
SELECT
hits.contentGroup.contentgroup2 AS CampaignGrouping,
custd.value AS member_PK,
PARSE_TIMESTAMP('%Y%m%d',date) AS date,
'WebMobile' AS Canal,
'MX' AS country_id,
SUM(hits.contentGroup.contentGroupUniqueViews2) AS VistasUnicas
FROM
`bigquery-xxxx-xxxxx.111111.ga_sessions*`,
UNNEST(customdimensions) custd,
UNNEST(hits) AS hits
WHERE
1 = 1
AND PARSE_TIMESTAMP('%Y%m%d', REGEXP_EXTRACT(_table_suffix, r'.*_(.*)')) BETWEEN TIMESTAMP('2017-06-01') AND TIMESTAMP('2017-06-30')
AND custd.index=30
and hits.contentGroup.contentGroup2 <> '(not set)'
AND custd.value <> 'null'
AND hits.contentGroup.contentGroupUniqueViews2 IS NOT NULL
GROUP BY 1, 2, 3, 4, 5
Below is for BigQuery Standard SQL, assuming there is a date field dt
that holds date info
#standardSQL
SELECT *
FROM yourTable
WHERE DATE_TRUNC(dt, MONTH) =
DATE_TRUNC(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), MONTH)
above assumes data type of dt field is DATE
In case if dt is STRING type - try below
#standardSQL
WITH yourTableAS (
SELECT '2017-05-30' AS dt UNION ALL
SELECT '2017-05-31' UNION ALL
SELECT '2017-06-01' UNION ALL
SELECT '2017-06-02' UNION ALL
SELECT '2017-06-03'
)
SELECT *
FROM yourTable
WHERE DATE_TRUNC(CAST(dt AS DATE), MONTH) =
DATE_TRUNC(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), MONTH)
In case if dt has different format than 'YYYY-MM-DD' you can use PARSE_DATE to CAST string to date
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.