在postgreSql中使用预准备语句的动态数据透视表

时间:2014-04-20 20:29:15

标签: mysql postgresql dynamic pivot prepared-statement

我希望转换Table1中的数据,如Pivot_table中数据的第一张图片所示。下面你可以看到Mysql中用于动态数据透视表的脚本,但我想在Postgresql中知道类似或合适的解决方案,如果可能的话?

Table1:
PK        Name     Subject     Grade**
-------------------------------------
1         Bob       Math        A
2         Bob       History     B
3         Bob       Language    C
4         Bob       Biology     D
5         Sue       History     C
6         Sue       Math        A
7         Sue       Music       A
8         Sue       Geography   C


Pivot_table:
Subject     Bob     Sue
-------------------------
Math        A        A
History     B        C
Language    C 
Biology     D
Music                A
Geography            C

Mysql中的脚本:

SET @sql = NULL;

SELECT GROUP_CONCAT(DISTINCT
         CONCAT('MAX(CASE WHEN name = ''', name,
                ''' THEN grade END) `', name, '`'))
  INTO @sql
  FROM table1;

SET @sql = CONCAT('SELECT subject, ', @sql, ' 
                     FROM table1 
                    GROUP BY subject');

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

非常感谢

0 个答案:

没有答案