在Google BigQuery中,我想并排显示两个不同日期的数据。我想显示今天的数据,然后是七天前的数据进行比较。我的FROM子句选择一系列表,每个表对应一个日期。
SELECT
DATE(TIMESTAMP(INTEGER(visitStartTime*1000000))) AS GMT_Date,
DAYOFWEEK(TIMESTAMP(INTEGER(visitStartTime*1000000))) AS GMT_Weekday,
IF(hits.customDimensions.index=15, hits.customDimensions.value, NULL) AS apikey,
hits.eventInfo.eventCategory AS event_category,
SUM(totals.visits) AS visit_count,
DATE(DATE_ADD(TIMESTAMP(INTEGER(visitStartTime*1000000)),-7,"DAY")) AS test,
// HERE I need to show SUM(totals.visits) but for the date of 'test' above
FROM (TABLE_DATE_RANGE([100610078.ga_sessions_], TIMESTAMP('20150529'),TIMESTAMP('20150711')))
WHERE
IF(hits.customDimensions.index=15, hits.customDimensions.value, NULL) IS NOT NULL
GROUP BY
GMT_Date,
GMT_Weekday,
event_category,
test,
apikey
ORDER BY
GMT_Date DESC,
visit_count DESC
LIMIT
30
在'测试'之后,我想显示测试日期的访问总和。我该怎么做?我在BigQuery语法页面上看不到任何与此相似的内容。
以下是其目前正在返回的图片:http://prntscr.com/7s8w58
在'测试'我希望像previous_week_visits这样的列与visit_count具有相同的数据但是需要测试日期。
答案 0 :(得分:2)
一种方法是使用窗口函数。您可以使用带固定基数的DATEDIFF将DATE映射到连续的INTEGER,然后使用LAG函数查找值,以下查询显示了此方法的示例:
select
d,
value,
lag(d, 3) over (order by diff) prev_d,
lag(value, 3) over (order by diff) prev_value
from (
select d, datediff(d, date('1970-01-01')) diff, value from
(select date('2012-01-01') d, 'a' value),
(select date('2012-01-02') d, 'b' value),
(select date('2012-01-03') d, 'c' value),
(select date('2012-01-04') d, 'd' value),
(select date('2012-01-05') d, 'e' value),
(select date('2012-01-06') d, 'f' value),
(select date('2012-01-07') d, 'g' value),
(select date('2012-01-08') d, 'h' value),
(select date('2012-01-09') d, 'i' value),
(select date('2012-01-10') d, 'j' value)
)
结果是:
Row d value prev_d prev_value
1 2012-01-01 a null null
2 2012-01-02 b null null
3 2012-01-03 c null null
4 2012-01-04 d 2012-01-01 a
5 2012-01-05 e 2012-01-02 b
6 2012-01-06 f 2012-01-03 c
7 2012-01-07 g 2012-01-04 d
8 2012-01-08 h 2012-01-05 e
9 2012-01-09 i 2012-01-06 f
10 2012-01-10 j 2012-01-07 g