数据透视表sql

时间:2012-03-30 12:06:04

标签: mysql sql pivot

需要数据库数据透视中的错误帮助。我有桌子驯服table_score如下:

|ID  | Subject | Score|
----------------------
|001 | 2GSLIG  | 80   |
|001 | 3ECITI  | 70   |
|002 | 2GSLIG  | 75   |
|002 | 3ECITI  | 85   |
-----------------------

然后它应该转入

|ID | 2GSLIG | 3ECITI |
-----------------------
|001|   80   |   70   |
|002|   85   |   75   |
-----------------------

我的代码是

SELECT
  ID,
  [2GSLIG] AS 2GSLIG,
  [3ECITI] AS 3ECITI
FROM
  (SELECT
     ID,
     Subject,
     Score
   FROM
     table_score) ps
PIVOT
 (SUM (Score)
  FOR Subject IN ( [2GSLIG], [3ECITI])) AS pvt

并且仍然是错误

#1064 - You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '[ 2GSLIG ] AS 2GSLIG , [ 3ECITI ] AS 3ECITI FROM ( SELECT ID ,
Subject , Score F' at line 1

我对此感到困惑,请帮助。谢谢。

2 个答案:

答案 0 :(得分:3)

怎么样 -

SELECT
    ID,
    SUM(IF(Subject = '2GSLIG', Score, 0)) AS `2GSLIG`,
    SUM(IF(Subject = '3ECITI', Score, 0)) AS `3ECITI`
FROM table_score
GROUP BY ID

答案 1 :(得分:2)

好像你忘记了''你的别名中的2GSLIG和2ECITI附近

SELECT ID, [2GSLIG] AS '2GSLIG', [3ECITI] AS '3ECITI' 
FROM (SELECT ID, Subject, Score FROM table_score ) AS ps PIVOT (SUM (Score) FOR Subject IN ( [2GSLIG], [3ECITI])) AS pvt