简体   繁体   中英

Dynamic query using bigquery and data studio

I want to take out data for every date range in Data Studio without the need to change date range selectors in my BigQuery all the time. However, not sure if it is even possible to do so. The reasons I do this is to make sure that the queried data is only for 30 days, as later it do some kind of segmentation using that 30 days data.

Then I figured out that the Data Studio can use dynamic_date, however this way will never produce any datatable (datatable will be used to do other queries from it). Is it possible to do dynamic_date in BigQuery instead? like retrieving data from BigQuery using a date range not previously defined in the query.

From my point of view, code should be like:

SELECT
   ID, 
   FROM `table`
   WHERE DATE(Timestamp) between $DS_START_DATE and  $DS_START_DATE + INTERVAL 30 DAY)

or

WHERE DATE(Timestamp) >= @DS_START_DATE

I believe in pure Bigquery you can use DECLARE clause for that purpose, defining variables of the specified type:

declare DS_START_DATE date default "2020-03-03";
declare DS_END_DATE date default "2020-03-04";

WITH sample AS (
  SELECT '10001' AS id,  cast('2020-03-01' AS timestamp) as date_id UNION ALL
  SELECT '10002', cast('2020-03-02' AS timestamp) UNION ALL
  SELECT '10003', cast('2020-03-03' AS timestamp) UNION ALL
  SELECT '10004', cast('2020-03-04' AS timestamp) UNION ALL
  SELECT '10005', cast('2020-03-05' AS timestamp) UNION ALL
  SELECT '10006', cast('2020-03-06' AS timestamp)
)
select id, date_id from sample

where date(date_id) between DS_START_DATE and DS_END_DATE 

Alternatively, you can take a look at parameterized queries , however as I mentioned in the comment, they are not supported in classic BigQuery web UI.

DECLARE is still not supported when using custom queries in Looker Studio (aka Data Studio), but it's possible to pass a date range into the query like shown below. Please note that the dates are passed as strings, hence parse_date is required.

WHERE DATE(Timestamp) >= parse_date('%Y%m%d', @DS_START_DATE)

There's also a predefined param @DS_END_DATE when enabling date range.

More info

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM