0

在使用旧版 sql 的 bigquery 中,我创建了一个可怕的查询,该查询返回以下我在 2018 年 2 月 26 日发布的网站的每日访问量显示:

Row  date       name    release_date  visits_count
1    20180226   a_name  20180226      2179
2    20180227   a_name  20180226      9522
3    20180228   a_name  20180226      1593   
4    20180301   a_name  20180226      300    
...

我真正想要的是

Row  name    release   count_release  count_release+1  count_release_rest
1    a_name  20180226  2179           9522             1893  

因此,我希望发布日期的实际访问次数、发布日期后的第二天以及之后的所有访问次数都应该相加。我是 bigquery 的新手(也是 sql 的新手......)。有没有办法将我的第一个显示定义为“子表”或类似的东西,以便我可以做到这一点,或者你会推荐什么方法?

4

2 回答 2

1

有很多方法可以实现此功能。最简单的方法是将日期与案例陈述进行比较。

select name, sum(case when date = relese_date then 1 else 0) as release_count, 
sum(case when date = DATE_ADD(relese_date,1,"DAY") then 1 else 0) as release_count1
sum(case when date > DATE_ADD(relese_date,1,"DAY") then 1 else 0) as release_count_other
于 2018-07-11T10:29:09.160 回答
0

以下是 BigQuery 标准 SQL

#standardSQL
WITH `project.dataset.table` AS (
  SELECT '20180226' date, 'a_name' name, '20180226' release_date, 2179 visits_count UNION ALL
  SELECT '20180227', 'a_name', '20180226', 9522 UNION ALL
  SELECT '20180228', 'a_name', '20180226', 1593 UNION ALL   
  SELECT '20180301', 'a_name', '20180226', 300  
)
SELECT name, release_date, 
  SUM(CASE WHEN date = release_date THEN visits_count END) count_release,
  SUM(CASE WHEN PARSE_DATE('%Y%m%d', date) = DATE_ADD(PARSE_DATE('%Y%m%d', release_date), INTERVAL 1 DAY) THEN visits_count END) count_release_next_day,
  SUM(CASE WHEN PARSE_DATE('%Y%m%d', date) > DATE_ADD(PARSE_DATE('%Y%m%d', release_date), INTERVAL 1 DAY) THEN visits_count END) count_release_rest
FROM `project.dataset.table`
GROUP BY name, release_date   

或以上可以“重构”以避免重复 PARSE_DATE,因此查询看起来更紧凑,更易于管理

#standardSQL
WITH `project.dataset.table` AS (
  SELECT '20180226' date, 'a_name' name, '20180226' release_date, 2179 visits_count UNION ALL
  SELECT '20180227', 'a_name', '20180226', 9522 UNION ALL
  SELECT '20180228', 'a_name', '20180226', 1593 UNION ALL   
  SELECT '20180301', 'a_name', '20180226', 300  
)
SELECT name, release_date, 
  SUM(CASE WHEN date = release_date THEN visits_count END) count_release,
  SUM(CASE WHEN visit = release_next_day THEN visits_count END) count_release_next_day,
  SUM(CASE WHEN visit > release_next_day THEN visits_count END) count_release_rest
FROM `project.dataset.table`, 
UNNEST([STRUCT<visit DATE, release_next_day DATE>(
  PARSE_DATE('%Y%m%d', date), 
  DATE_ADD(PARSE_DATE('%Y%m%d', release_date), INTERVAL 1 DAY))]) x
GROUP BY name, release_date      

在这两种情况下,结果都是

Row name    release_date    count_release   count_release_next_day  count_release_rest   
1   a_name  20180226        2179            9522                    1893     
于 2018-07-11T13:14:15.687 回答