首页 > 解决方案 > Bigquery - 选择一个列而不将它们分组在按子句中

问题描述

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

我的要求是,查询当月表现最好的产品,只知道设备和用户的类型。我不想根据 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 上的问题不起作用。

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

标签: google-bigquery

解决方案


从技术上讲,您可以使用ANY_VALUE或or来封装device_category和:user_typeMAXMIN

 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;

推荐阅读