在MySQL中的Concat sql sum

时间:2016-01-15 15:33:54

标签: mysql sql

有没有办法在sum中使用group_concat收益率或任何解决方法?

我有以下查询,它会返回item_iditems.title字段的冗余结果:

SELECT
  item_id, sum(qty), items.title, units.title
  FROM invoice_items
  LEFT JOIN items
   ON item_id = items.id
    LEFT JOIN units ON invoice_items.unit_id = units.id
 GROUP BY item_id, invoice_items.unit_id ORDER BY items.id, units.weight DESC;

我尝试使用group_concat来连接多余的行,如下所示:

SELECT
sum(qty),  group_concat(item_id, items.title, sum(qty) SEPARATOR '-')
  FROM invoice_items
  LEFT JOIN items
   ON item_id = items.id
    LEFT JOIN units ON invoice_items.unit_id = units.id
 GROUP BY item_id, invoice_items.unit_id ORDER BY items.id, units.weight DESC;

但是,它会返回此错误:Invalid use of group function

我想要的是将sum产量连接在一行中,而不是任何其他字段。

以下是查询结果的屏幕截图:

enter image description here

我需要第一行:

item_id: 1
sum(qty): 2, 13, 5
title: اسبوسيد أقراص

1 个答案:

答案 0 :(得分:2)

使用您的查询做另一个group by(使用适当的列名作为子查询):

SELECT item_id, title, GROUP_CONCAT(sumqty)
FROM (SELECT ii.item_id, sum(qty) as sumqty, i.title
      FROM invoice_items ii LEFT JOIN
           items i
           ON ii.item_id = i.id LEFT JOIN
           units u
           ON ii.unit_id = u.id
     GROUP BY ii.item_id, ii.unit_id
    ) ii
GROUP BY item_id;