I have the following MySQL statement that works perfectly. However I now need a total as designated in bold square brackets/parenthesis below.
SELECT f.fid, r.tid, r.tbd, r.tbc, r.tc, r.tname, r.category,
SUM(`time`) AS `totaltime`,
SUM(`points`) AS `points`,
(SELECT IFNULL(SUM(points),0) FROM Primes WHERE zid = r.zid AND wid = r.wid AND s_id = 38) AS `cl`,
(SELECT IFNULL(SUM(points),0) FROM Primes WHERE zid = r.zid AND wid = r.wid AND s_id = 34) AS `sp`,
**[sum points + climb + sprint] AS pointstotal**
FROM teams f
JOIN results r
ON f.wid = r.wid
WHERE r.rank <= 3 AND r.id = '254293' AND r.category = 'C'
AND r.fin = '1'
GROUP BY f.fid
ORDER BY pointstotal DESC
I have tried many different permutations etc and multiple references in other questions but I just cant get it to work.
The simplest way is to move your query into a subquery, and then add those columns.
SELECT fid, tid, tbd, tbc, tc, tname, category, totaltime,
points, cl, sp, points + cl + sp AS pointstotal
FROM (
SELECT f.fid, r.tid, r.tbd, r.tbc, r.tc, r.tname, r.category,
SUM(`time`) AS `totaltime`,
SUM(`points`) AS `points`,
(SELECT SUM(points) FROM Primes WHERE zid = r.zid AND wid = r.wid AND s_id = 38) AS `cl`,
(SELECT SUM(points) FROM Primes WHERE zid = r.zid AND wid = r.wid AND s_id = 34) AS `sp`
FROM teams f
JOIN results r
ON f.wid = r.wid
WHERE r.rank <= 3 AND r.id = '254293' AND r.category = 'C'
AND r.fin = '1'
GROUP BY f.fid
) AS x
ORDER BY pointstotal DESC
But I generally dislike correlated subqueries, I prefer joins, and then you don't need another level
SELECT SELECT f.fid, r.tid, r.tbd, r.tbc, r.tc, r.tname, r.category,
SUM(time) AS totaltime, SUM(points) AS points,
cl, sp, SUM(POINTS) + cl + sp AS totalpoints
FROM teams AS f
JOIN results AS r ON f.wid = r.wid
JOIN (
SELECT zid, wid, SUM(IF(s_id = 38, points, 0)) AS cl, SUM(IF(s_id = 34, points, 0)) AS sp
FROM Primes
GROUP BY zid, wid
) AS p ON p.zid = r.zid AND p.wid = r.wid
WHERE r.rank <= 3 AND r.id = '24293' AND r.category = 'C' AND r.fin = '1'
GROUP BY f.fid
ORDER BY pointstotal DESC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.