SQL grouping Multi-column statistics (group by criteria by post)-Go

Source: Internet
Author: User

Today, in the garden, we see an example of a group by grouping multi-column statistics, and we'll share it with you:

CREATE TABLE Tests (year datetime year to Year,type char (1), value int);
ALTER TABLE tests ALTER COLOMN year INT;

INSERT into tests values (2015,1,100);
INSERT into tests values (2015,2,200);
INSERT into tests values (2016,1,150);
INSERT into tests values (2016,2,300);
INSERT into tests values (2016,3,100);

Year TYPE VALUE
2015 1 100
2015 2 200
2016 1 150
2016 2 300
2016 3 100

Into

Year TYPE1 TYPE2 TYPE3
2015 100 200 0
2016 150 300 100

At this time we need case when,sql in addition to group by:

SELECT year, sum (case if type=1 then value else 0 end) as type1, sum (case if type=2 then value else 0 END) as type2, S UM (Case-type=3 then value-ELSE 0 END) as Type3, from Table_test GROUP by year

SQL grouping Multi-column statistics (group by criteria by post)-Go

Related Article

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.