2016-05-29 80 views
1

問題:Mysql的問題與組由兩列

我有一些比賽結果的表。對於每輛車,有兩名車手分別獲勝。爲了便於工作,我爲每輛車創建了一行表格(所以兩個驅動程序分爲兩列: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.所以,當我希望看到每個驅動程序在兩站比賽的總得分,這應該是結果:

  1. 邁克爾:40
  2. 裏克:20
  3. 喬希:20
  4. 史蒂夫:16
  5. 湯姆:16

但我怎麼組的得分爲每個驅動程序處理的驅動(驅動1和驅動2)的兩列?或者我只需要更改我的表格併爲每個驅動程序創建一行?

$sql = "SELECT race, driver1, driver2, points FROM `example-table` GROUP BY ………. ORDER BY `points` DESC"; 

回答

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

正是我需要的。謝謝! – Stan

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