用CASE语句构造BigQuery中的查询

时间:2016-02-11 03:17:33

标签: google-bigquery

所以我正在尝试在BigQuery中构建一个我正在努力争取最终部分的查询。

截至目前,我有:

SELECT
UNIQUE(Name) as SubscriptionName,
ID,
Interval,
COUNT(mantaSubscriptionIdmetadata) AS SubsPurchased,
SUM(RevenueGenerated) as RevenueGenerated
FROM (
SELECT
mantaSubscriptionIdmetadata,
planIdmetadata,
INTEGER(Amount) as RevenueGenerated
FROM
[sample_internal_data.charge0209]
WHERE
revenueSourcemetadata = 'new'
AND
Status = 'Paid'
GROUP BY
mantaSubscriptionIdmetadata,
planIdmetadata,
RevenueGenerated
 )a
JOIN (
SELECT
id,
Name,
Interval
FROM
[sample_internal_data.subplans]
WHERE
id in ('150017','150030','150033','150019')
GROUP BY
id,
Name,
Interval )b
ON
a.planIdmetadata = b.id
GROUP BY
ID,
Interval,
Name
ORDER BY
Interval ASC 

The resulting query looks like this 这正是我到目前为止所期待的。

现在我坚持这个。我需要添加另一个名为SalesRepName的列。结果字段将为null或不为null。如果它为null则表示它在线销售。如果它不为空,则表示它是通过电话销售的。我想要做的是创建两个额外的列,其中显示通过电话销售和在线销售的数量。两列的总和将始终等于SubsPurchased总数。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

您可以在聚合函数中包含case语句。您可以在此处选择sum(case when SalesRepName is null then 1 else 0 end) as onlinesum(case when SalesRepName is not null then 1 else 0 end) as telesales

count(case when SalesRepName is null then 1 end) as online会得到相同的结果。在这些情况下使用sum只是我个人的偏好。

请注意,省略else子句相当于设置else null,而null不会被count计算。这与exact_count_distinct结合使用非常有用,sum在{{1}}方面没有等效内容。

答案 1 :(得分:0)

尝试以下内容:
它假设您的SalesRepName字段位于[sample_internal_data.charge0209]表中 然后它使用SUM(CASE ... WHEN ...)的“微小版本”,当你需要0或1作为SUM'ed的时候它可以工作

  

SUM(SalesRepName IS NULL)AS onlinesales,
  SUM(不是SalesRepName IS NULL)AS telsales

SELECT
  UNIQUE(Name) AS SubscriptionName,
  ID,
  Interval,
  COUNT(mantaSubscriptionIdmetadata) AS SubsPurchased,
  SUM(RevenueGenerated) AS RevenueGenerated, 
  SUM(SalesRepName IS NULL) AS onlinesales,
  SUM(NOT SalesRepName IS NULL) AS telesales
FROM (
  SELECT SalesRepName, mantaSubscriptionIdmetadata, planIdmetadata, INTEGER(Amount) AS RevenueGenerated
  FROM [sample_internal_data.charge0209]
  WHERE revenueSourcemetadata = 'new'
    AND Status = 'Paid'
  GROUP BY mantaSubscriptionIdmetadata, planIdmetadata, RevenueGenerated
 )a
JOIN (
  SELECT id, Name, Interval
  FROM [sample_internal_data.subplans]
  WHERE id IN ('150017','150030','150033','150019')
  GROUP BY id, Name, Interval
)b
ON a.planIdmetadata = b.id
GROUP BY ID, Interval, Name
ORDER BY Interval ASC