简体   繁体   English

使用 `string_agg` 在 BigQuery SQL 中创建一个包含另一个连接的唯一元素的新列

[英]Create a new column containing the concatenated unique elements of another in BigQuery SQL, using `string_agg`

Given the following data:给定以下数据:

WITH abc AS 
(
  SELECT 1234 id, 'Aug' month, 'P' value UNION ALL
  SELECT 1234, 'Sept', 'P' UNION ALL
  SELECT 4567, 'Sept', 'D' 
)
SELECT 
    month, 
    value, 
FROM abc

Which looks as:看起来像:

在此处输入图像描述

I'd like to create a new column values which contains all values from the value columns.我想创建一个新列values ,其中包含value列中的所有值。

So for this example data the new column would contain P, D .因此,对于此示例数据,新列将包含P, D

Having done this the output would be (I've just written this out in Excel):完成此操作后,output 将是(我刚刚用 Excel 将其写出来):

在此处输入图像描述

I tried to do this as follows:我尝试按如下方式执行此操作:

WITH abc AS 
(
    SELECT 1234 id, 'Aug' month, 'P' value 
    UNION ALL
    SELECT 1234, 'Sept', 'P' 
    UNION ALL
    SELECT 4567, 'Sept', 'D' 
)
SELECT 
    month, 
    value, 
    STRING_AGG(distinct value, " & ") as str_agg
FROM abc

But I get this error:但我收到此错误:

SELECT list expression references column month which is neither grouped nor aggregated at [7:5] SELECT 列表表达式引用列月份,它既没有分组也没有聚合在 [7:5]

I'm not sure how to aggregate/group the value column in order to satisfy this error.我不确定如何聚合/分组value列以满足此错误。

Use below在下面使用

select * 
from abc, (
  select string_agg(distinct value, ', ') values
  from abc
)

if applied to sample data in your question - output is如果应用于您问题中的示例数据 - output 是

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 谷歌 Bigquery SQL UNNEST 和 STRING_AGG - Google Bigquery SQL UNNEST and STRING_AGG 如何在 BigQuery 中编写条件 string_agg 函数? - How can I write a conditional string_agg function in BigQuery? 如何使用 SQL 在表中创建一个新列以仅显示来自另一列的特定数据? - How can I create a new column in a table to show only specific data from another column using SQL? 使用 bigquery 中具有字符串列的另一个表更新 bigquery 中的结构列 - Update a struct column in bigquery using another table in bigquerry having string columns 如何使用 Google BigQuery 中数组类型列的不同元素进行分组? - How to Group By using the distinct elements of an Array type column in Google BigQuery? 如何将列名字符串作为参数传递到 BigQuery 中的 CREATE TABLE FUNCTION - How to pass a string of column name as a parameter into a CREATE TABLE FUNCTION in BigQuery 创建新的 sql 列以获得新的价值 - create new sql column to get new value 使用另一个字段 BigQuery 在带有分隔符的字段中获取字符串的 Position - Get Position of a String in a field with delimiters using ANOTHER field BigQuery 如何根据 BigQuery 中的唯一值对元素进行计数 - How to count elements based on a unique value in BigQuery 使用 BigQuery 计算列中重复记录之间的不同记录 SQL - Count Distinct Records between a repeating record in column using BigQuery SQL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM