我最近尝试使用GROUP_CONCAT完成聚合,其中,对于每个相似的值,我将所有重复项都作为查询。
根据invoice_number列,我想查询所有类似的项目,并在字符串中查询group_concat。
但是,我只能检索找到的第一个值和group_concat它们。我真的需要根据共享相同发票号的项目数量来拥有多个类似串联的字符串。
这是我的表:
发票表
|item_id |invoice_number |amount |currency|
|-----------|---------------|-------|--------|
|379406 |INV00000046 |52286 |USD |
|567501 |INV00000046 |52286 |USD |
|102448 |INV00000390 |0 |USD |
|1975291 |INV00000390 |0 |USD |
|62436 |INV00000390 |0 |USD |
|4067502 |INV00000346 |35112 |EUR |
|5174950 |INV00000346 |35112 |EUR |
期望的结果
|item_id |related items |amount |currency|
|-----------|-----------------------|-------|--------|
|379406 |379406,567501 |52286 |USD |
|567501 |379406,567501 |52286 |USD |
|102448 |102448,1975291,62436 |0 |USD |
|1975291 |102448,1975291,62436 |0 |USD |
|62436 |102448,1975291,62436 |0 |USD |
|4067502 |4067502,5174950 |35112 |EUR |
|5174950 |4067502,5174950 |35112 |EUR |
我写的查询是:
SELECT
item_id,
invoice_number,
GROUP_CONCAT(item_id) as shared_item_ids,
ROUND(AVG(amount)/100,2) as invoice_amount,
currency
FROM
invoices
GROUP BY
invoice_number,
currency
答案 0 :(得分:0)
只需使用invoice_number作为密钥即可自行加入表格。
SELECT
invoices.item_id,
invoices.invoice_number,
GROUP_CONCAT(related.item_id) as shared_item_ids,
ROUND(AVG(amount)/100,2) as invoice_amount,
currency
FROM invoices
JOIN invoices related ON related.invoice_number = invoices.invoice_number
GROUP BY invoices.item_id
答案 1 :(得分:0)
试试这个sql,希望它能帮到你。
index=False
如果您有问题,请告知我