简体   繁体   English

MySQL问题按两列分组

[英]Mysql issue with group by two columns

The problem: 问题:

I have a table with some race results. 我有一张桌子,上面有一些比赛结果。 For each car there are two drivers who each win points individually. 每辆车都有两名驾驶员,每人分别赢得积分。 To facilitate the work, I created a table with one row for each car (so with the two drivers in two columns: driver1, driver2) instead of one for each driver, because apart from the driver all the other columns have the same value for each car. 为了简化工作,我创建了一个表格,其中每辆车都有一行(因此,两个驾驶员分为两列:driver1,driver2),而不是每个驾驶员一个,因为除了驾驶员以外,所有其他列的值都相同每辆车。

Example: 例:

+------+-----+---------+---------+--------+
| 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   |
+------+-----+---------+---------+--------+

As you can see there are more than two drivers for car number 1. So when I want to see the total score for each driver over the two races, this should be the result: 如您所见,1号车厢有两个以上的驾驶员。因此,当我想查看两个种族中每个驾驶员的总得分时,应该是这样的结果:

  1. Michael: 40 迈克尔:40
  2. Rick: 20 瑞克:20
  3. Josh: 20 乔希:20
  4. Steve: 16 史蒂夫:16
  5. Tom: 16 汤姆:16

But how do I group the score for each driver dealing with two columns of drivers (driver1 and driver2) ? 但是,如何对处理两列驱动程序(driver1和driver2)的每个驱动程序的得分进行分组? Or do I simply have to change my table and create a row for each driver? 还是只需要更改表并为每个驱动程序创建一行?

$sql = "SELECT race, driver1, driver2, points FROM `example-table` GROUP BY ………. ORDER BY `points` DESC";
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

You could use the union all operator to query the drivers as a single column, and then group by the driver and sum the points: 您可以使用union all运算符以单列形式查询驱动程序,然后group by驱动程序group bysum

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

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

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