BigQuery在本周和上周获取数据

时间:2018-09-04 12:04:27

标签: google-bigquery

假设我有一个查询:

SELECT ga_channelGrouping, ga_sourceMedium, SUM(ga_sessionDuration)/SUM(ga_sessions) as avg_sessionDuration 

FROM database.table 

group by ga_channelGrouping, ga_sourceMedium

如果我有一个BigQuery的{​​{1}}列,如何从DATE中选择上周本周的数据}}。

1 个答案:

答案 0 :(得分:2)

DATE_TRUNC是有用的功能,它可以让您开始一周的开始,而DATE_SUB可以让您到达上周

DATE_TRUNC

DATE_SUB

SELECT if(date(date) >= DATE_TRUNC(current_date(), WEEK(MONDAY)),"This Week","Last Week") weekPeriod, 
 ga_channelGrouping, 
 ga_sourceMedium, 
 SUM(ga_sessionDuration)/SUM(ga_sessions) as avg_sessionDuration 

FROM database.table 
WHERE date(date) > = DATE_SUB(DATE_TRUNC(current_date(), WEEK(MONDAY)), INTERVAL 1 WEEK)
group by weekPeriod, ga_channelGrouping, ga_sourceMedium

如果您的一周从星期日开始,只需将 WEEK(MONDAY)更改为 WEEK(SUNDAY)