Mysql查询将行动态转换为列并求和

时间:2018-03-23 17:07:54

标签: mysql

MySQL可以将列转换为行,动态添加行所需的列数。我尝试了其他解决方案,但他们似乎没有解决我的独特案例。 这是包含数据的表

表A

    +---------+-------------+------+
    |driver_id|stage_name   |points|
    +---------+-------------+------+
    |1        |Stage 1 50cc |20    |
    +---------+-------------+------+
    |1        |Stage 2 50cc |17    |
    +---------+-------------+------+
    |2        |Stage 1 50cc |17    |
    +---------+-------------+------+
    |2        |Stage 2 50cc |15    |
    +---------+-------------+------+
    |3        |Stage 1 75cc |17    |
    +---------+-------------+------+
    |3        |Stage 2 75cc |15    |
    +---------+-------------+------+
    |4        |Stage 1 75cc |15    |
    +---------+-------------+------+
    |4        |Stage 2 75cc |20    |
    +---------+-------------+------+

我想查询格式如下

    +---------+-------------+-------------+-------------+-------------+--------------+
    |driver_id|Stage 1 50cc |Stage 2 50cc |Stage 1 75cc |Stage 2 75cc | Total Points |
    +---------+-------------+-------------+-------------+-------------+--------------+
    |1        |     20      |     17      |    null     |    null     |    37        |
    +---------+-------------+-------------+-------------+-------------+--------------+
    |2        |     17      |     15      |    null     |    null     |    32        |
    +---------+-------------+-------------+-------------+-------------+--------------+
    |3        |     null    |     null    |     16      |     15      |    31        |
    +---------+-------------+-------------+-------------+-------------+--------------+
    |4        |     null    |     null    |     15      |    20       |    35        |
    +---------+-------------+-------------+-------------+-------------+--------------+

正如您所看到的,最后一个col的计算基于该驱动程序的各个阶段的总和。 总和现在不是很重要,但首先得分,但如果一切皆有可能那么精彩。

1 个答案:

答案 0 :(得分:0)

我会以这种方式存储数据(或者可能在规范化中更进一步):

+-----------+----------+----+--------+
| driver_id | stage_no | cc | points |
+-----------+----------+----+--------+
|         1 |        1 | 50 |     20 |
|         1 |        2 | 50 |     17 |
|         2 |        1 | 50 |     17 |
|         2 |        2 | 50 |     15 |
|         3 |        1 | 75 |     17 |
|         3 |        2 | 75 |     15 |
|         4 |        1 | 75 |     15 |
|         4 |        2 | 75 |     20 |
+-----------+----------+----+--------+

然后我会使用这个查询:

SELECT driver_id, stage_no, cc, points FROM my_table ORDER BY driver_id,stage,cc;

然后我将在应用程序代码中处理其他所有内容。