0

I have one table named grades like this:

  +--------+--------+-----------+
  | userid | itemid | finalgrade|
  +--------+--------+-----------+
  |  1     |   7    |    100    | 
  |  1     |   8    |    89     |    
  |  2     |   7    |    87     |     
  |  2     |   8    |    17     |    
  |  3     |   7    |    87     |   
  |  3     |   8    |    38     |   
  +--------+--------+-----------+

And I want to create a pivot query that changes me the table like this:

  +--------+---+---+
  | userid | 7 | 8 |
  +--------+---+---+
  |  1     |100| 89| 
  |  2     |87 | 17|        
  |  3     |87 | 38|    
  +--------+---+---+

I have one solution, using defined itemid like this one:

select *,
truncate (sum(finalgrade*(1-abs(sign(itemid-7)))),0) as 7,
truncate (sum(finalgrade*(1-abs(sign(itemid-8)))),0) as 8,
FROM grades
group by userid"

The problem is that I need the same query but with not defined itemid, dynamically creating columns.

1 Answer 1

1

I think that you want a query like this:

SELECT userid,
  MAX(CASE WHEN itemid=7 THEN finalgrade END) as c7,
  MAX(CASE WHEN itemid=8 THEN finalgrade END) as c8,
FROM grades
GROUP BY userid

but you want it with dynamic values, and then you could use a prepared statement like this:

SELECT    
  CONCAT(    
    'SELECT userid,',    
    GROUP_CONCAT(CONCAT('MAX(CASE WHEN itemid=', itemid, ' THEN finalgrade END) AS c', itemid)),    
    ' FROM tablename GROUP BY userid')    
FROM (SELECT DISTINCT itemid FROM tablename) s INTO @sql;

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

You could use SUM instead of MAX, depending on how your data is structured.

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for the solution, but the query have a syntax error: 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 'PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt' at line 8.
@EnriqueBerrueta it looks correct to me: sqlfiddle.com/#!2/7e8f4/1 is itemid a INT column?
Yes, item id is INT. I was using sqlfiddle and surprise me because its correct, the problem is when i use it in phpmyadmin or in php.
@EnriqueBerrueta do you have a lot of different itemids? group_concat has a length limit and i suspect that the query might have been cut... but this limit can be modified using set group_concat_max_len=<new limit>; its default is 1024 you could try with 10000...
Yes, this help me a little, but now the query gives me another error: Unknown prepared statement handler (stmt) given to EXECUTE
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.