mysql select 动态行作为列名

mysql select dynamic rows as column names

Student_id | Skill_id  | skill-Score
1              30            5
1              50            1
1              63            2
1              42            2

2              30            7
2              50            3
2              63            6
2              42            9

我正在尝试创建这种格式的 table 我该怎么做。?

Student_id ||    30   ||     50   ||     63   ||    42   |
    1             5          1           2           2
    2             7          3           6           9

这里是我试过但没有结果请不要考虑我的尝试。

SELECT CONCAT(
  'SELECT `r_job_scores`.id_score', GROUP_CONCAT('
     ,    `t_', REPLACE(skill_id, '`', '``'), '`.value
         AS `', REPLACE(skill_id, '`', '``'), '`'
     SEPARATOR ''),
 ' FROM `r_job_scores` ', GROUP_CONCAT('
     LEFT JOIN `r_job_scores`   AS `t_', REPLACE(skill_id, '`', '``'), '`
            ON `r_job_scores`.id_score = `t_', REPLACE(skill_id, '`', '``'), '`.id_score
           AND `t_', REPLACE(skill_id, '`', '``'), '`.skill_id = ', QUOTE(skill_id)
     SEPARATOR ''),
 ' GROUP BY `r_job_scores`.id_score'
)

如果技能 ID 的数量已知且固定,则可以使用简单的数据透视查询:

SELECT Student_Id,
       MAX(CASE WHEN Skill_id = 30 THEN skill-Score END) AS `30`,
       MAX(CASE WHEN Skill_id = 50 THEN skill-Score END) AS `50`,
       MAX(CASE WHEN Skill_id = 63 THEN skill-Score END) AS `63`,
       MAX(CASE WHEN Skill_id = 42 THEN skill-Score END) AS `42`
FROM r_job_scores
GROUP BY Student_Id

如果您想获得学生总分,一种方法是子查询我上面给出的查询并计算总数:

SELECT t.Student_Id,
       t.`30` + t.`50` + t.`63` + t.`42` AS overall_score
FROM
(
    SELECT Student_Id,
           MAX(CASE WHEN Skill_id = 30 THEN skill-Score END) AS `30`,
           MAX(CASE WHEN Skill_id = 50 THEN skill-Score END) AS `50`,
           MAX(CASE WHEN Skill_id = 63 THEN skill-Score END) AS `63`,
           MAX(CASE WHEN Skill_id = 42 THEN skill-Score END) AS `42`
    FROM r_job_scores
    GROUP BY Student_Id
) t

您可以使用动态 sql 实现此目的。

查询

set @query = null;
select
  group_concat(distinct
    concat(
      'max(case when `Skill_id` = ',
      `Skill_id`, ' then `skill-Score` end) as `', `Skill_id` , '`'
    )
  ) into @query
from `your_table_name`;

set @query = concat('select `Student_id`, ', @query, ' from `your_table_name` 
              group by `Student_id`
');

prepare stmt from @query;
execute stmt;
deallocate prepare stmt;

输出

+------------+----+----+----+----+
| Student_id | 30 | 50 | 63 | 42 |
+------------+----+----+----+----+
| 1          | 5  | 1  | 2  | 2  |
| 2          | 7  | 3  | 6  | 9  |
+------------+----+----+----+----+

SQL Fiddle demo