MYSQL/查询 : How to make table rows into column

标签 mysql

我有 3 个表 tbl_contestant、tbl_criteria 和 tbl_judges。然后我将另外 1 个表组合这 3 个表作为我的结果,tbl_score。

tbl_criteria
------------------------
crit_id | criteria_name
   16   |    sports

tbl_judges
------------------------
judge_id  |   judge_name
   61     |    first
   62     |    second
   63     |    third


 tbl_cotestant
--------------------------------------
con_id  |  contestant_number | contestant_name |
   1    |         1          |      john       |
   2    |         2          |       sy        |
   3    |         3          |       Nah       |


tbl_score
--------------------------------------------------
score_id | crit_id | judge_id | contestant_number |   score
   1     |    16   |    61    |        1          |     25  
   2     |    16   |    61    |        2          |     25
   3     |    16   |    61    |        3          |     25
   4     |    16   |    62    |        1          |     25  
   5     |    16   |    62    |        2          |     73
   6     |    16   |    62    |        3          |     59
   7     |    16   |    63    |        1          |     70  
   8     |    16   |    63    |        2          |     80
   9     |    16   |    63    |        3          |     70

如何实现这个输出,judge_id行根据crit_id变成列

contestant_number | contestant_name | 16_judge_61 | 16_judge_62 | 16_judge_63 | total
        1         |       john      |       25    |      25     |     70      |     
        2         |       sy        |       25    |      73     |     80      |
        3         |       Nah       |       25    |      59     |     70      |  

请更正我的问题

SELECT DISTINCT(c.contestant_number) , contestant_name , j1.sports as 
16_judge_61, j2.sports as 16_judge_62, j3.sports as 16_judge_63 from
tbl_criteria , tbl_score, tbl_contestant c 
LEFT JOIN tbl_ // <-- i have no idea how start from here joining those 4 tables together

最佳答案

您可以使用 CASE WHEN 来解决这个问题。

SELECT 
      s.contestant_number,
      c.contestant_name,
      SUM(CASE WHEN s.crit_id='16' AND s.judge_id='61' THEN s.score END) as 16_judge_61,
      SUM(CASE WHEN s.crit_id='16' AND s.judge_id='62' THEN s.score END) as 16_judge_62,
      SUM(CASE WHEN s.crit_id='16' AND s.judge_id='63' THEN s.score END) as 16_judge_63,
      SUM(s.score) as Total
    FROM tbl_score s
      INNER JOIN tbl_contestant c ON s.contestant_number = c.contestant_number
      GROUP BY s.contestant_number

参见 SQL Fiddle http://sqlfiddle.com/#!9/9efa5/1

关于MYSQL/查询 : How to make table rows into column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39434767/

相关文章:

php - 构建没有项目 ID 的 URL 并获得正确的项目

php - 理解 Laravel 关系 - 它们没有意义......?

php - MySQL:如何将文本预先附加到现有列中的数据?

php - 存储过程中的 OUT 参数声明

mysql - 如何从group_concat mysql的结果中获取最大值

php - 在 php.ini 文件中保存 MySQL 用户名/密码安全吗?

php - 如何使用php水平显示数据库中的所有文件?

mysql - 在多对多字段表关系中再次添加字段可以吗?

MySQL多种索引类型?

php - Ajax 和 PHP - 插入错误