我来整份现代的写法,使用pivot,希望能帮到你
create table dbo.usr ( name varchar(10), age int, sex char(1) ) insert into dbo.usr values('a',18,'f'),('b',19,'m'),('c',20,'f'),('d',21,'m') select p.sex,count(0) as usercount, sum(p.[18]) as [age=18], sum(p.[19]) as [age=19],sum(p.[20]) as [age=20],sum(p.[21]) as [age=21] from dbo.usr u PIVOT ( count(age) for age in([18],[19],[20],[21]) ) as p group by p.sex
先按照sex分组,再用到行转列函数 处理age。
--传统的解法 SELECT sex,
count(*) as count, SUM(CASE WHEN age = 18 THEN 1 ELSE 0 END) AS 'age=18', SUM(CASE WHEN age = 19 THEN 1 ELSE 0 END) AS 'age=19', SUM(CASE WHEN age = 20 THEN 1 ELSE 0 END) AS 'age=20' FROM person GROUP BY sex