问题:
我有一张桌子上有一些比赛结果。对于每辆车,有两名车手各自分别赢得积分。为了方便工作,我为每辆车创建了一个表格(因此两个驱动程序分为两列:driver1,driver2)而不是每个驱动程序一个,因为除了驱动程序之外,所有其他列都具有相同的值每辆车。
示例:
+------+-----+---------+---------+--------+
| race | car | driver1 | driver2 | points | + other variables with same value for both drivers
+------+-----+---------+---------+--------+
| GER | 1 | Michael | Rick | 20 |
| GER | 2 | Steve | Tom | 8 |
| JAP | 1 | Michael | Josh | 20 |
| JAP | 2 | Steve | Tom | 8 |
+------+-----+---------+---------+--------+
正如你所看到的,对于1号车来说,有两个以上的车手。所以当我想看到两个赛车中每个车手的总得分时,结果应该是这样的:
但是如何为每个处理两列驱动程序(driver1和driver2)的驱动程序分数?或者我只需要更改我的表并为每个驱动程序创建一行?
$sql = "SELECT race, driver1, driver2, points FROM `example-table` GROUP BY ………. ORDER BY `points` DESC";
答案 0 :(得分:1)
SELECT driver, SUM(points) as points
FROM
(SELECT driver1 as driver, points
FROM `example-table`
UNION ALL
SELECT driver2 as driver, points
FROM `example-table`)T
GROUP BY driver
答案 1 :(得分:1)
您可以使用union all
运算符将驱动程序作为单个列进行查询,然后group by
驱动程序和sum
点:
SELECT driver, SUM(points)
FROM (SELECT driver1 AS driver, points FROM example_table
UNION ALL
SELECT driver2 AS driver, points FROM example_table) t
GROUP BY driver
ORDER BY 2 DESC