An SQL sentence

Source: Internet
Author: User

SQL statement Query

The table structure is as follows: ID name gender 1 Zhang San male 2 Wang 4 male 3 Lili female 4 Zhang San male 5 Zhao Liu male 6 Gao Jie male 7 Wang 4 female 8 Gao Jie female 9 Zhang San female how can I use an SQL statement to query the following result shows the number of men and women in the name. The number of men and women includes ID Zhang 3 3 2 1 1 1 4, 9 King 4 2 1 Lili 1 0 1 3 Gao Jie 2 1 6 6 8 Zhao Liu 1 1 0 5

Select * from (select distinct name, count (ID) as number of people,

Sum (case when sex = 'male' then 1 else 0 end) as men,

Sum (case when sex = 'female' then 1 else 0 end) as female count

From test group by name)

Outer apply (

Select

[Include id] = stuff (replace (

(

Select ID from Test N

Where name = A. Name

For XML auto

), '<N id = "', ','), '"/>', ''), 1, 1 ,'')

) N

 

 

 

 

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.