如何生成每个ID的字符串列表?

时间:2018-10-04 19:58:28

标签: postgresql

我想列出每个客户购买的品牌。我有相同的“ customer_id”字段重复出现,它们使用在此代码中购买的不同品牌的名称(显示为列标题:“ name”)。我想按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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

这仅汇总品牌名称:

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