A SQL statement to count the number of identical names
Source: Internet
Author: User
SQL statement Query
The table structure is like this:
ID name Sex
1 Three men
2 Wang Shinan
3 Lili Girl
4 Three Men
5 Chao Liuan
6 Noble Male
7 Wang Shiju
8 Noble Women
9 Three Girls
How can I query the following results with an SQL statement
Names, number of men, numbers of women, including IDs.
Zhang 33 2 1 1,4,9
Wang 42 1 1 2,7
Lili 1 0 1 3
Noble 2 1 1 6,8
Zhao Liu 1 1 0 5
Copy Code code as follows:
SELECT * FROM (select DISTINCT name,count (ID) as human numbers,
SUM (case when sex= "man" then 1 else 0 end) as man,
SUM (case when sex= "female" then 1 else 0 end) as Woman
From Test GROUP by Name A
OUTER APPLY (
SELECT
[Contains id]= STUFF (replace (
(
SELECT ID from Test N
WHERE Name = A.name
For XML AUTO
), "<n id=" ",", ")," "/>", "" "), 1, 1," ")
) N
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