如何为每个 id 生成一个字符串列表? [复制]

Posted

技术标签:

【中文标题】如何为每个 id 生成一个字符串列表? [复制]【英文标题】:How do I generate a list of strings per id? [duplicate] 【发布时间】:2019-03-10 06:59:55 【问题描述】:

我想列出每个客户购买的品牌。我有相同的“customer_id”字段反复出现,并带有他们在此代码中购买的不同品牌的名称(显示为列标题:“名称”)。我想按 customer_id 分组并显示每个 customer_id 的品牌列表。我收到错误消息:

“错误:函数 group_concat(字符变化,未知)不 存在 ^ 提示:没有函数匹配给定的名称和参数类型。你可能需要 添加显式类型转换。

    CREATE TEMP TABLE customer_brandids AS 
SELECT receipts.receipt_id, receipts.customer_id, receipt_item_details1.brand_id
FROM receipts
LEFT JOIN receipt_item_details1
ON receipts.receipt_id = receipt_item_details1.receipt_id;

SELECT customer_brandids.customer_id, customer_brandids.brand_id, brands.name, GROUP_CONCAT(brands.name,',')
FROM customer_brandids
INNER JOIN brands
ON customer_brandids.brand_id = brands.brand_id
GROUP by customer_id

【问题讨论】:

试试 string_agg。 group_concat 是不是mysql 您在Postgres manual 的哪个位置找到group_concat 【参考方案1】:
CREATE TEMP TABLE customer_brandids AS 
SELECT receipts.receipt_id, receipts.customer_id, receipt_item_details1.brand_id
FROM receipts
LEFT JOIN receipt_item_details1
ON receipts.receipt_id = receipt_item_details1.receipt_id;

SELECT customer_brandids.customer_id, customer_brandids.brand_id, brands.name, string_agg(brands.name,',')
FROM customer_brandids
INNER JOIN brands
ON customer_brandids.brand_id = brands.brand_id
GROUP by customer_id

【讨论】:

感谢我运行它并将“GROUP BY customer_id”替换为“GROUP BY customer_brandids.customer_id”我收到此错误消息:“列“customer_brandids.brand_id”必须出现在 GROUP BY 子句中或被使用在聚合函数 LINE 1: SELECT customer_brandids.customer_id, customer_brandids.bran... 我如何只按 customer_id 聚合? @lschra01,你不能,除非你把它变成一个聚合体。我不知道你在那里有非聚合字段并且不包含在 group by 中。如果您不关心每个 customer_id 获得哪个brand_id,或者每个 customer_id 是唯一的(brand.name 相同),那么您可以执行以下操作:max(customer_brandids.brand_id) as brand_id。 - 或者简单地将它们添加到分组依据。【参考方案2】:

这仅聚合品牌名称:

SELECT cb.customer_id, ARRAY_AGG(b.name) as brand_names
FROM customer_brandids cb
INNER JOIN brands b
ON cb.brand_id = b.brand_id
GROUP by cb.customer_id

如果您还想要品牌 ID 列表:

SELECT 
    cb.customer_id, 
    ARRAY_AGG(b.brand_id) as brand_ids,
    ARRAY_AGG(b.name) as brand_names
FROM customer_brandids cb
INNER JOIN brands b
ON cb.brand_id = b.brand_id
GROUP by cb.customer_id

如果您需要将列表作为字符串列表,请使用 string_agg 而不是 array_agg

SELECT 
    cb.customer_id, 
    string_agg(b.brand_id, ',') as brand_ids, -- delete this line if you only need the names
    string_agg(b.name, ',') as brand_names
FROM customer_brandids cb
INNER JOIN brands b
ON cb.brand_id = b.brand_id
GROUP by cb.customer_id

【讨论】:

谢谢!只需列出每个客户 _id 购买的品牌,用逗号分隔每个品牌。 我添加了一个 string_agg 查询。更好? 我没有?我以为我做到了

以上是关于如何为每个 id 生成一个字符串列表? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

如何为字段的每个唯一值生成随机记录?

如何为每位新访客创建唯一ID?

如何为所有动态生成的 div 添加常用的 Javascript 函数? [复制]

如何为 JS Array.includes() 提供 equals/hash 函数? [复制]

如何为这个在每个阶段都有移动平均线的 df 创建一个 while 循环? [复制]

如何为列表中的每个项目添加一个布尔值?