下面是我的表结构,我想将其转换为另一种格式(从行到列类型)我已经尝试了很多但是我无法这样做。
StudentID | Mark | Subject
-------------------------
10 |46 |Java
--------------------------
10 |65 |C#
--------------------------
10 |79 |JavaScript
---------------------------
11 |66 |Java
--------------------------
11 |85 |C#
--------------------------
11 |99 |JavaScript
--------------------------
O / P应该是:
StudentID | Java | C# | JavaScript
---------------------------------
10 | 46 | 65 | 79
---------------------------------
11 | 66 | 85 | 99
-------------------------------
答案 0 :(得分:5)
此类数据转换称为 pivot 。 MySQL没有pivot函数,因此您需要使用带有CASE
表达式的聚合函数来转换数据。
如果您提前知道变换的值,那么您可以对它们进行类似的硬编码:
select studentid,
sum(case when subject = 'Java' then mark else 0 end) Java,
sum(case when subject = 'C#' then mark else 0 end) `C#`,
sum(case when subject = 'JavaScript' then mark else 0 end) JavaScript
from yourtable
group by studentid
如果主题的值未知或灵活,那么您可能希望使用预准备语句来生成动态sql:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'sum(case when subject = ''',
subject,
''' then mark else 0 end) AS `',
subject, '`'
)
) INTO @sql
FROM yourtable;
SET @sql = CONCAT('SELECT studentid, ', @sql, '
from yourtable
group by studentid');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
两个查询的结果是:
| STUDENTID | JAVA | C# | JAVASCRIPT |
--------------------------------------
| 10 | 46 | 65 | 79 |
| 11 | 66 | 85 | 99 |