SQL GROUP_CONCAT + SUM + AVG

a 夏天 提交于 2019-12-23 06:22:25

问题


SELECT *,
       Group_concat(rating) AS rating_total,
       Sum(rating_total)    AS rating_sum,
       Avg(rating_sum)      AS rating_avg
FROM   ratings
GROUP  BY pid  

For some reason the sum and average don't execute....how do you make this statement work?


回答1:


Because of the way that SQL compiles the queries (I assume MySQL since you're using GROUP_CONCAT), you cannot reference aliased column names before the order by clause. The SUM and AVG functions are not procedural. They are done in parallel. Which means that they can't be dependent.

Secondly, GROUP_CONCAT returns a string, not a number. How to you hope to SUM/AVG that? Just SUM and AVG the rating column in and of itself.

Now, given this, you could do:

SELECT
    pid,
    GROUP_CONCAT(rating) AS rating_total,
    SUM(rating) as rating_sum,
    AVG(rating) as rating_avg
FROM
    rating
GROUP BY
    pid

This should get you what you're looking for.




回答2:


GROUP_CONCAT returns a string, concatenating all the selected valuse. Then, you are trying to sum that string and then you are trying to get the average of the sum.

I think you need to use SUM and AVG upon values from the table, not the result of concatenation.



来源:https://stackoverflow.com/questions/931594/sql-group-concat-sum-avg

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