【问题标题】:How do I generate a list of strings per id? [duplicate]如何为每个 id 生成一个字符串列表? [复制]
【发布时间】: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

标签: postgresql


【解决方案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 查询。更好?
  • 我没有?我以为我做到了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
  • 2018-08-03
  • 1970-01-01
相关资源
最近更新 更多