MYSQL horizontal Data Display _ MySQL

Source: Internet
Author: User
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;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.