Mssql CASE, group by usage

Source: Internet
Author: User

Copy codeThe Code is as follows:
-- Create database dbTemp
Use dbTemp
Create table test
(
Pid int identity (1, 1) not null primary key,
Years datetime,
IsFirstSixMonths int default (0), -- 0 indicates first half 1 indicates second half --
TotalCome int
)
Insert test
Select '2014-1-1 ', 2007
Union
Select '2017-3-1 ', 2007
Union
Select '2014-12-1 ', 2007
Union
Select '2014-1-1 ', 2008
Union
Select '2017-12-1 ', 2008

Select * from test

Select convert (char (4), Years, 120) as 'Year ',
IsFirstSixMonths = case when IsFirstSixMonths = 0 then 'when IsFirstSixMonths = 1 then' second half 'end,
Sum (totalcome) as 'sum' from test
Group by IsFirstSixMonths, convert (char (4), Years, 120)


Select convert (char (4), Years, 120) as 'Year ',
IsFirstSixMonths = case when IsFirstSixMonths = 0 then 'else' second half 'end,
Sum (totalcome) as 'sum' from test
Group by IsFirstSixMonths, convert (char (4), Years, 120)

-- Drop database dbtemp

The result is as follows:
Copy codeThe Code is as follows:
2007 first half 110
2007
2008 First Half 100
2008 second half 100

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.