MYSQL SUM TWO COLUMNS

razer :

I have this situation:

SELECT uf.*, SUM(uto.points) AS total_points_live, 
             SUM(utl.points) AS total_points_online,
             (total_points_live + total_points_online) AS total_points
FROM users AS uf    
            LEFT JOIN users_tourney_online AS uto
                ON uto.id_users = uf.id 
            LEFT JOIN users_tourney_live AS utl
                ON utl.id_users = uf.id
GROUP BY uf.id ORDER BY total_points DESC

But not working because aliases cannot be used.

Can you help me?

Regards,

GMB :

You cannot use an alias defined in the same SELECT clause it is defined.

You would need to repeat the expression:

SUM(uto.points) + SUM(utl.points) AS total_points

If the SUMs may be NULL:

COALESCE(SUM(uto.points), 0) + COALESCE(SUM(utl.points), 0) AS total_points

Alternatively, you can use a subquery:

SELECT t.*, coalesce(total_points_live, 0) + coalesce(total_points_online, 0) total_points
FROM (
    SELECT uf.*, SUM(uto.points) AS total_points_live, SUM(utl.points) AS total_points_online
    FROM ...
    GROUP BY uf.id
) t
ORDER BY total_points desc

Unrelated note: GROUP BY and SELECT * do not go along well together; it is a good practice to enumerate all non-aggregated columns in the GROUP BY clause (although MySQL is somewhat lax about it).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=401470&siteId=1