【问题标题】:Bigquery - Select a column with not grouping them in group by clauseBigquery - 选择一列而不将它们分组在按子句中
【发布时间】:2021-02-16 15:43:33
【问题描述】:

我有基于 device_category(desktop/mobile/tablet) 和 user_type(new user/returning user) 的 google 分析数据的按日表。

我的要求是,查询当月表现最好的产品,只知道设备和用户的类型。我不想根据 device_category、user_type 对它们进行分组。

当从我的查询中排除它们时,会出现错误提示 - “查询错误:SELECT 列表表达式引用列 device_category 在 [3:21] 时既不分组也不聚合

查询无效(这是我的要求)

 SELECT
  month, 
  year, 
  device_category, 
  user_type, 
  product_name, 
  round(sum(item_revenue),2) as item_revenue 
FROM 
  `ProjectName.DatasetName.GA_REPORT_3_*` 
where 
  _table_suffix between '20201101' and '20210131' 
  and channel_grouping = 'Organic Search' 
group by 
  month, 
  year, 
  channel_grouping, 
  product_name 
order by 
  item_revenue desc;

有效的查询

SELECT 
  month, 
  year, 
  device_category, 
  user_type, 
  product_name, 
  round(sum(item_revenue),2) as item_revenue 
FROM 
  `ProjectName.DatasetName.GA_REPORT_3_*` 
where 
  _table_suffix between '20201101' and '20210131' 
  and channel_grouping = 'Organic Search' 
group by 
  month, 
  year, 
  channel_grouping, 
  product_name, 
  device_category, 
  user_type 
order by 
  item_revenue desc;

样本数据

我知道在常规 SQL 工作台中,我们可以在 SQL 中选择一个列,而不是在 Group By 子句中,但这对于我在 Bigquery 上的问题不起作用。

你能帮我解决这个问题吗?

【问题讨论】:

  • 示例数据以及格式化您的查询以便其他人可以阅读它们在这里会非常有帮助。
  • 如果您不将user_typedevice_category 包含在分组中,这意味着您的计算sum(item_revenue) 将“在它们之上”求和。这意味着,它将在sum(item_revenue) 计算中包含多个user_typesdevice_category。因此,如果您选择它们​​,但不按它们分组,您希望在这些列中看到什么值?每行将有多个值...我建议您尝试创建一个包含所需结果的电子表格,然后您就会明白我的意思。

标签: google-bigquery


【解决方案1】:

从技术上讲,您可以用ANY_VALUEMAXMIN 封装device_categoryuser_type

 SELECT
  month, 
  year, 
  ANY_VALUE(device_category), 
  ANY_VALUE(user_type), 
  product_name, 
  round(sum(item_revenue),2) as item_revenue 
FROM 
  `ProjectName.DatasetName.GA_REPORT_3_*` 
where 
  _table_suffix between '20201101' and '20210131' 
  and channel_grouping = 'Organic Search' 
group by 
  month, 
  year, 
  channel_grouping, 
  product_name 
order by 
  item_revenue desc;

【讨论】:

    【解决方案2】:

    您可以使用子查询来实现:

    SELECT 
      x.month, 
      x.year, 
      x.device_category, 
      x.user_type, 
      x.product_name, 
      ROUND(SUM(x.item_revenue),2) as item_revenue 
    FROM 
     (SELECT
        month,
        year,
        device_category,
        user_type,
        product_name,
        item_revenue
      FROM `ProjectName.DatasetName.GA_REPORT_3_*` 
      WHERE _table_suffix BETWEEN '20201101' and '20210131' 
      AND channel_grouping = 'Organic Search'
     ) x 
    GROUP BY 
      x.month, 
      x.year,  
      x.product_name, 
      x.device_category, 
      x.user_type 
    ORDER BY ROUND(SUM(x.item_revenue),2) DESC;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 2012-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多