这个问题在这里已有答案:
我想列出每个客户购买的品牌。我有相同的“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
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
这只汇总了品牌名称:
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