有没有办法在sum
中使用group_concat
收益率或任何解决方法?
我有以下查询,它会返回item_id
和items.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
产量连接在一行中,而不是任何其他字段。
以下是查询结果的屏幕截图:
我需要第一行:
item_id: 1
sum(qty): 2, 13, 5
title: اسبوسيد أقراص
答案 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;