【发布时间】:2018-04-21 05:11:17
【问题描述】:
我最近尝试使用 GROUP_CONCAT 完成聚合,其中对于每个相似的值,我都有所有重复的项目正在查询。
根据 invoice_number 列,我想查询所有相似的项目,并将它们分组到一个字符串中。
但是,我只能检索找到的第一个值并 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
【问题讨论】:
标签: mysql group-concat