总和两次和组

时间:2015-02-14 10:41:31

标签: php mysql pdo

我有这样的表:

| ID | Team   | User    | Try1 | Try2 |  Try3 |
| 1  | Black  | Chris   |  2   |  6   |  4    |
| 2  | Black  | Brian   |  10  |  8   |  10   |
| 3  | Red    | Mark    |  6   |  2   |  8    |
| 4  | Red    | Andrew  |  4   |  10  |  6    |

我需要将团队尝试点数计算在一起以获得总数。

SELECT *, SUM(Try1 + Try2 + Try3) AS total FROM team_pts GROUP BY team ORDER BY total DESC

问题是 - 如何为每次尝试输出每个团队的总数? 像这样:

| Pos | Team  | Try1 | Try2 | Try3 | Total |
|  1  | Black |  12  |  14  |  14  |  40   |
|  2  | Red   |  10  |  12  |  14  |  36   |

抱歉我的英文!

2 个答案:

答案 0 :(得分:1)

SELECT ID,Team,SUM(Try1)为Try1,SUM(Try2)为Try2,SUM(Try3)为Try3,SUM(Try1 + Try2 + Try3)AS Total FROM team_pts GROUP BY team ORDER BY total DESC

答案 1 :(得分:1)

您需要在总和之前对列进行求和:

SELECT *,
       SUM(Try1),
       SUM(Try2),
       SUM(Try3),
       SUM(Try1 + Try2 + Try3) AS total
FROM team_pts
GROUP BY team
ORDER BY total DESC