A classic summary SQL statement

Source: Internet
Author: User

Table Structure:
Environment of time place names
1 Beijing excellent
2 Beijing is good
3 Beijing difference
4 good Tianjin
5 Tianjin is good
6 Shanghai difference

Expected results:
Excellent location
Beijing 1 1 1
Tianjin 2 0 0
Shanghai 0 0 1

Create Table T ([date] int identity (1, 1), place nvarchar (10), circumstance nvarchar (10 ))
Insert T select n 'beijing', N 'excellent'
Union all select n 'beijing', n 'good'
Union all select n 'beijing', n' Difference'
Union all select n 'tianjin ', n' good'
Union all select n 'tianjin ', n' good'
Union all select n 'shanghai', n 'Difference'

Select place [location],
Sum (Case circumstance when n 'excellent 'Then 1 else 0 end) [excellent],
Sum (Case circumstance when n 'excellent 'Then 1 else 0 end) [good],
Sum (Case circumstance when n' difference 'then 1 else 0 end) [difference]
From t
Group by Place

Drop table t
/*
Excellent location
-------------------------------------------
Shanghai 0 0 1
Tianjin 0 2 0
Beijing 1 1 1
*/

Select
Uncd,
Sum (Case infoty when '1' then 1 else 0 end) as Morning Post,
Sum (Case infoty when '2' then 1 else 0 end) as delay,
Sum (Case infoty when '3' then 1 else 0 end) as underreporting,
Sum (Case infoty when '4' then 1 else 0 end) as error message
From st_infsmry_c
Group by uncd

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.