BigQuery使用MAX()函数

时间:2016-06-09 18:44:42

标签: sql google-bigquery

所以我在BQ中有一个看起来如此的查询:

SELECT
  SubscriptionId,
  start_time,
 STRFTIME_UTC_USEC((UTC_USEC_TO_MONTH(TIMESTAMP_TO_USEC(TIMESTAMP(start_time)))),'%B %Y') AS cohort_month,
  UTC_USEC_TO_MONTH(start_time) AS usec_month,
  STRFTIME_UTC_USEC((UTC_USEC_TO_WEEK(TIMESTAMP_TO_USEC(TIMESTAMP(start_time)), 0)),'%Y-%m-%d') AS cohort_week,
  WEEK(start_time) AS usec_week,
  DATE(start_time) AS cohort_day,
  UTC_USEC_TO_DAY(start_time) AS usec_day,
  amount,
  current_period_start,
  current_period_end,
  cancel_date,
  end_date,
  cancel_at_period_end,
  salesRepEmail,
  CASE WHEN (salesRepEmail IS NOT NULL) THEN 'Telesales' ELSE 'Online' END AS sales_channel,
  status,
  type_id,
  CASE WHEN (type_id IN ('150032',
      '150033',
      '150023')) THEN 'Annual' ELSE 'Monthly' END AS duration,
  refunded
FROM
  [data_snapshots_daily.subs_charges_refunds_]
WHERE
  start_time >= '2016-04-01 00:00:00'
  AND refunded = FALSE

我想要做的是添加查询,以便返回最近一个月,一周和一天的所有相关数据。

所以我想它与MAX(usec_month)有关,但我无法弄明白。请记住,我只希望它在最近一个月(6月)中包含相关数据时返回

1 个答案:

答案 0 :(得分:1)

我想到下面的内容

当月?

WHERE YEAR(CURRENT_DATE()) = YEAR(start_time)
AND MONTH(CURRENT_DATE()) = MONTH(start_time)

本周

WHERE YEAR(CURRENT_DATE()) = YEAR(start_time)
AND WEEK(CURRENT_DATE()) = WEEK(start_time)

当天

WHERE CURRENT_DATE() = DATE(start_time)
  

快速添加

过去两周玩下面的事情(应该改进以处理一年中的第一周)

WHERE (YEAR(CURRENT_DATE()) = YEAR(start_time) AND WEEK(CURRENT_DATE()) = WEEK(start_time))
OR CASE WHEN WEEK(CURRENT_DATE()) = 1 
      THEN (YEAR(CURRENT_DATE()) - 1 = YEAR(start_time) AND 53 = WEEK(start_time))
      ELSE (YEAR(CURRENT_DATE()) = YEAR(start_time) AND WEEK(CURRENT_DATE()) - 1 = WEEK(start_time))
    END
  

以上陈述的细分(根据您的要求)

它查找属于当前或上周的开始时间。本周很简单。在前一周的情况下,它看起来当前周不是一年中的第一周 - 在这种情况下条件是 - 同一年但前一周。如果当前一周是一年中的第一周 - 它会查找上一年的最后一周。

  

更清洁的版本来处理last two weeks条件

DATE(start_time)>DATE(DATE_ADD(CURRENT_DATE(),-7*1-DAYOFWEEK(CURRENT_DATE()),'DAY'))

更改1中的7*1让我们说3 - 会为您提供last four weeks的条件,例如