MYSQL horizontal display data recently prepared interview questions, want to interview a company before encountered an SQL question, horizontal display of a table data, did not write a summary at that time, so as not to forget.
-- ---------------------------- Table structure for 't_ subobject' -- ---------------------------- drop table if exists 't_ subobject'; create table 't_ subobject' ('id' int (11) not null default '0', 'name' varchar (255) default null, 'subobject' varchar (255) default null, 'result' int (11) default null, primary key ('id') ENGINE = InnoDB default charset = utf8; -- returns Records of t_subject -- -------------------------- insert into't _ subject 'values ('1', 'xiaoming ', 'China', '50'); insert into 't_ subject 'values ('2', 'xiaoming ', 'mat', '20 '); insert into't _ subject 'values ('3', 'Happy ', 'English', '000000'); insert into't _ subject 'values ('4 ', 'Happy ', 'China', '123'); insert into't _ subject 'values ('5', '小', 'mat', '123 ');
There is a table that contains three people with three subjects.
SELECT t. name, SUM (IF (t. subject = 'China', t. results, 0) AS 'China', SUM (IF (t. subject = 'mat', t. results, 0) as 'mate', SUM (IF (t. subject = 'English ', t. results, 0) as 'English 'FROM t_subject tGROUP BY (t. name );
The execution result is as follows:
At that time, I was curious why I needed to add the SUM function for SUM. after removing it, I executed the following SQL statement:
If this function is not added for preliminary analysis, SQL execution only counts the grouped data by default.
SELECT*FROMt_subject tGROUP BY t.name;