简体   繁体   English

如何对 MySQL 中的子查询求和

[英]How to sum subqueries in MySQL

I have the following MySQL statement that works perfectly.我有以下完美运行的 MySQL 语句。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM