Simple SQL statement Statistics monthly data per month for each column of data, simple SQL exercise

Source: Internet
Author: User

There is a table with the following data

Please write the SQL statement with the result as follows.

Create a table in MySQL

CREATE TABLE ' AA ' (
' id ' int (ten) not NULL auto_increment COMMENT ' book Number ',
' Year ' varchar (4) is not NULL DEFAULT ' COMMENT ',
' Month ' varchar (2) Not NULL DEFAULT ' 0 ' COMMENT ' month ',
' Mount ' double DEFAULT NULL COMMENT ' quantity ',
PRIMARY KEY (' id ')
) Engine=innodb DEFAULT Charset=utf8;

Insert data:

INSERT into AA (Year,month,mount) VALUES (2011,1,1.1), (2011,2,1.2), (2011,3,1.3), (2011,4,1.4);
INSERT into AA (Year,month,mount) VALUES (2012,1,2.1), (2012,2,2.2), (2012,3,2.3), (2012,4,2.4);
INSERT into AA (Year,month,mount) VALUES (2013,1,3.1), (2013,2,3.2), (2013,3,3.3), (2013,4,3.4);
INSERT into AA (Year,month,mount) VALUES (2014,1,4.1), (2014,2,4.2), (2014,3,4.3), (2014,4,4.4);

The query statements are:

Select T2.year, (select T1.mount from AA t1 where t1.year = t2.year and T1.month = 1) M1,
(select T1.mount from AA t1 where t1.year = t2.year and t1.month = 2) m2,
(select T1.mount from AA t1 where t1.year = t2.year and t1.month = 3) M3,
(select T1.mount from the AA t1 where t1.year = t2.year and T1.month = 4) M4 from
AA T2 GROUP BY t2.year Order by T2.year;

Complete.

Note: Simple implementation of a bit, if you have a better, if it is convenient to share, if anything wrong, please point out, thank you!

Simple SQL statement Statistics monthly data per month for each column of data, simple SQL exercise

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.