Bigquery:如何根据特定时间范围汇总几列的数据?

时间:2020-08-29 13:30:13

标签: sql syntax google-bigquery

我是大型查询的新手,我正在尝试汇总一系列客户帐户中的交易数据,收入数据和访问者数据。我需要按客户名称和8个月的时间对输出进行分组,因此每个客户帐户都具有12个月的汇总数据(每月的每一天都添加到一个月的条目中)。我只能设法摆脱每个月的第一天,而不能将两者之间的所有内容加在一起:

SELECT
  clientname,
  DATE_TRUNC(PARSE_DATE('%Y%m%d',date), MONTH) as MonthStart,
  SUM (totals.visits) AS visits,
  SUM (totals.transactions) AS transactions,
  SUM (totals.campaigns) AS campaigns,
  sum (totals.totalTransactionRevenue) AS Transactionsrevenue,
FROM `prod.mar.auto` as automotive
GROUP BY 
   clientname,monthstart
ORDER BY 
   clientname,monthstart ASC
Limit 1000

输出仅提供月份的第一天的值,而不提供月份之间的总和。有人可以帮我指出正确的方向吗?

谢谢

2 个答案:

答案 0 :(得分:0)

如果要获取最近8或12个月的数据,请使用WHERE子句:

SELECT a.clientname,
       SUM(a.visits) AS visits,
       SUM(a.transactions) AS transactions,
       SUM(a.campaigns) AS campaigns,
       SUM(a.totalTransactionRevenue) AS Transactionsrevenue,
FROM `prod.mar.auto` as a
WHERE PARSE_DATE('%Y%m%d',date >= DATE_ADD(CURRENT_DATE interval -12 months)
GROUP BY clientname
ORDER BY clientname ASC
Limit 1000;

答案 1 :(得分:0)

部分问题尚不清楚,因此,我将尽我所能提供信息。

据我对您的问题的理解,似乎整个月的汇总都存在问题。它只会返回一个月的某一天,而不是整个月的总和。

如果您更改

DATE_TRUNC(PARSE_DATE('%Y%m%d',date), MONTH) as MonthStart

EXTRACT(MONTH FROM DATE) AS MonthStart

这将返回月份数,因此您可以进行汇总,因为所有日期字段中的数字对于每个月而言都是相同的。

这是最后一个查询:

SELECT
  clientname,
EXTRACT(MONTH FROM DATE) AS MonthStart,
  SUM (totals.visits) AS visits,
  SUM (totals.transactions) AS transactions,
  SUM (totals.campaigns) AS campaigns,
  sum (totals.totalTransactionRevenue) AS Transactionsrevenue,
FROM `prod.mar.auto` as automotive
GROUP BY 
   clientname, MonthStart
ORDER BY 
   clientname, MonthStart ASC
Limit 1000

提供功能文档: https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions