mysql's method of converting column values into columns

  • 2020-05-15 02:25:33
  • OfStack


--  Create the library 
CREATE TABLE `rate` (
 `uname` VARCHAR (300),
 `object` VARCHAR (300),
 `score` VARCHAR (300)
); 
--  Insert data 
INSERT INTO test.rate (uname, object, score)
 VALUES('aaa', 'chinese', '67'),
 ('aaa', 'math', '89'),
 ('aaa', 'physical', '89'),
 ('bbb', 'chinese', '67'),
 ('bbb', 'math', '75'),
 ('bbb', 'physical', '89');

--  The query 
SELECT DISTINCT uname AS ' The name ',
SUM(CASE object
WHEN 'chinese' THEN score END)  AS ' Chinese language and literature ',
SUM(CASE object
WHEN 'math' THEN score END)  AS ' mathematics ',
SUM(CASE object
WHEN 'physical' THEN score END)  AS ' physical ' FROM rate GROUP BY uname;


Related articles: