How to use sum() within a group_concat()?

为君一笑 提交于 2019-12-05 04:22:51

Change:

group_concat(CAST(quantity AS CHAR))

To

SUM(quantity)

--

SELECT s.`state`, i.`item`, SUM(i.`quantity`) AS quantities
FROM `shops` AS s
    LEFT JOIN `items` AS i ON i.`shop` = s.`shopid`
WHERE s.`state` = 5
GROUP BY i.`item`

Found a way to do this :

SELECT state,GROUP_CONCAT(cast(total as char))
FROM
(
    SELECT state,SUM(i.quantity) total
    FROM shops s
    LEFT JOIN items i ON i.shop=s.shopid
    WHERE state=5
    GROUP by item
) s

As far as I know you can't do that in MySQL. Dynamic columns are only supported to the extent of group_contcat() which still aggregates multiple results rows into a single column.

Only if you have a fixed/limited number of Total X-s, you can declare them in the query explicitely per se.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!