charcoalite
charcoalite

Reputation: 43

pivot table sql

need help in error in database pivot. i have table tamed table_score like below:

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

then it should be pivotted into

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

my code is

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

and it remains error

#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

I am getting confuse with this, need help please. Thank you.

Upvotes: 2

Views: 1325

Answers (2)

user1191247
user1191247

Reputation: 12973

How about -

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

Upvotes: 3

Darren
Darren

Reputation: 70776

Looks like you forgot the '' around 2GSLIG and 2ECITI in your aliases

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

Upvotes: 2

Related Questions