MySQL 8.0: implementing ORDER BY on Calculated Columns with GROUP BY
After trying multiple solutions online, I still can't figure this out. I just started working with Hey everyone, I'm running into an issue that's driving me crazy. I am working with unexpected behavior when trying to use `ORDER BY` on a calculated column in my MySQL 8.0 query that also uses `GROUP BY`. I expected the results to be sorted based on the calculated value, but instead, they seem to be ordered in a way that doesn't match my expectations. Hereโs the query I'm using: ```sql SELECT user_id, COUNT(order_id) AS total_orders, AVG(order_amount) AS avg_order_amount FROM orders GROUP BY user_id ORDER BY avg_order_amount DESC; ``` The intention here was to get the average order amount per user and order the results by that average. However, when I run this query, I receive an behavior saying `behavior 1055 (42000): 'orders.avg_order_amount' isn't in GROUP BY`. I have already enabled `ONLY_FULL_GROUP_BY` in my SQL mode, thinking it would enforce best practices for grouping. Iโve tried several approaches, such as using `HAVING` instead of `WHERE`, but I still encounter the same scenario. Hereโs another variation I attempted: ```sql SELECT user_id, COUNT(order_id) AS total_orders, AVG(order_amount) AS avg_order_amount FROM orders GROUP BY user_id HAVING avg_order_amount > 100 ORDER BY avg_order_amount DESC; ``` Still no luck! The behavior continues, and I need to seem to find a workaround. Additionally, I checked the MySQL documentation regarding `ORDER BY` and `GROUP BY`, but it hasn't clarified the scenario for me. Does anyone know how to correctly order by a calculated column in this scenario, or is there a more appropriate approach I should consider? Any insights or solutions would be greatly appreciated! For context: I'm using Sql on Ubuntu. I'm using Sql latest in this project. Has anyone dealt with something similar? This is for a web app running on CentOS.