Convert rows to columns in mysql

Below is my table structure, and I want to convert it to a different format (from row to column type). I tried a lot, but I can not do this.

StudentID | Mark | Subject
-------------------------
10        |46    |Java
--------------------------
10        |65    |C#
--------------------------
10        |79    |JavaScript
---------------------------
11        |66    |Java
--------------------------
11        |85    |C#
--------------------------
11        |99    |JavaScript
--------------------------

O / P Should be:

StudentID | Java | C# | JavaScript
---------------------------------
10        |  46  | 65 |   79
---------------------------------
11        |  66  | 85 |  99
-------------------------------
+2
source share
1 answer

This type of data transformation is known as a bar. MySQL does not have a summary function, so you will want to convert the data using an aggregate function with an expression CASE.

If you know the values ​​ahead of time to convert, you can hardcode them similar to this:

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

See SQL Fiddle with Demo .

, 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;

SQL Fiddle with Demo.

:

| STUDENTID | JAVA | C# | JAVASCRIPT |
--------------------------------------
|        10 |   46 | 65 |         79 |
|        11 |   66 | 85 |         99 |
+4

All Articles