如何将行值作为列名提取在Mysql中

时间:2015-08-22 09:10:38

标签: mysql

我需要以下方案的帮助。我们如何在行名称中动态获取行中的不同值?

我有以下格式的数据..

 Sno  firstName Subject   Marks
 1     ABC         Eng      10
 2     PQR         Hindi    20
 3     LM          Telgu    20 
 4     LM          Hindi    20
 5     LM          Eng      39

我需要以下格式输出。

Sno   FirstName    Eng    Hindi   Telgu
  1      ABC        10     Null    Null
  2     PQR        Null    20      Null
  3      LM         39     20       20

如果添加了另外一个主题,则应该将查询动态写入足以包含这些值...

如何为此查询?

1 个答案:

答案 0 :(得分:0)

你好Abecee在评论解决方案中告诉你你的问题是转动表。

以下是对您的表格的查询

SELECT Sno, firstName, 
      SUM(CASE WHEN Subject = 'Eng' THEN Marks ELSE NULL END) AS Eng,
      SUM(CASE WHEN Subject = 'Hindi' THEN Marks ELSE NULL END) AS Hindy,
      SUM(CASE WHEN Subject = 'Telgu' THEN Marks ELSE NULL END) AS Telgu
FROM t1
GROUP BY firstName
ORDER BY Sno

这是SQL Fiddle,看看它是如何运作的......

GL!

修改

好的基于this bluefeet 这里的答案是针对您的问题的动态解决方案

SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT 
        CONCAT('SUM(CASE WHEN Subject = ''',
                Subject,
               ''' THEN Marks ELSE NULL END) AS ',
               REPLACE(Subject, ' ', ''))) INTO @sql
FROM t1;

SET @sql = CONCAT('SELECT Sno, firstName, ', @sql, ' 
                  FROM t1
                  GROUP BY firstName
                  ORDER BY Sno');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

本节的第一部分

SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT 
        CONCAT('SUM(CASE WHEN Subject = ''',
                Subject,
               ''' THEN Marks ELSE NULL END) AS ',
               REPLACE(Subject, ' ', ''))) INTO @sql
FROM t1;

是动态创建我写的第一个查询的这部分

 SUM(CASE WHEN Subject = 'Eng' THEN Marks ELSE NULL END) AS Eng,
 SUM(CASE WHEN Subject = 'Hindi' THEN Marks ELSE NULL END) AS Hindy,
 SUM(CASE WHEN Subject = 'Telgu' THEN Marks ELSE NULL END) AS Telgu

第二部分是创建预备语句并将动态创建的部分包含在此

SELECT Sno, firstName, 
       -- here you add dynamically created part @sql
FROM t1
GROUP BY firstName
ORDER BY Sno

你在这部分代码中用CONCAT做到了

SET @sql = CONCAT('SELECT Sno, firstName, ', @sql, ' 
                  FROM t1
                  GROUP BY firstName
                  ORDER BY Sno');

当你从那个字符串创建它时,你准备语句并执行它

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

希望现在有点清楚......

以下是SQL Fiddle,因此您可以看到您可以比较两个查询并了解它的工作方式。

GL!

P.S。如果您有任何问题,请填写下面的评论