|
发表于 2020-1-16 11:00:01
|
显示全部楼层
create table #temp
(
name varchar(10),
age1 int,
age2 int,
age3 int,
age4 int,
age5 int,
age6 int
)
select * from #temp
insert into #temp values('张三',80,50,52,92,20,10)
insert into #temp values('李四',75,81,63,40,23,85)
insert into #temp values('小五',93,78,77,50,26,33)
select aaa.name 户主姓名,aaa.age6075 [60<年龄<75],bbb.age7590 [75<年龄<90],ccc.age90 [年龄>90]
from
(
select a.name,isnull(b.age6075,0) age6075
from #temp a,
(
select aa.name,isnull(count(*),0) as age6075 from
(
select name,age1 as age6075
from #temp
where age1>=60 and age1<75
union all
select name,age2
from #temp
where age2>=60 and age2<75
union all
select name,age3
from #temp
where age3>=60 and age3<75
union all
select name,age4
from #temp
where age4>=60 and age4<75
union all
select name,age5
from #temp
where age5>=60 and age5<75
union all
select name,age6
from #temp
where age6>=60 and age6<75
) aa
group by aa.name
) b
where a.name*=b.name
) aaa,
-----
(
select a.name,isnull(b.age7590,0) age7590
from #temp a,
(
select aa.name,isnull(count(*),0) as age7590 from
(
select name,age1 as age7590
from #temp
where age1>=75 and age1<90
union all
select name,age2
from #temp
where age2>=75 and age2<90
union all
select name,age3
from #temp
where age3>=75 and age3<90
union all
select name,age4
from #temp
where age4>=75 and age4<90
union all
select name,age5
from #temp
where age5>=75 and age5<90
union all
select name,age6
from #temp
where age6>=75 and age6<90
) aa
group by aa.name
) b
where a.name*=b.name
) bbb,
----
(
select a.name,isnull(b.age90,0) age90
from #temp a,
(
select aa.name,isnull(count(*),0) as age90 from
(
select name,age1 as age90
from #temp
where age1>=90
union all
select name,age2
from #temp
where age2>=90
union all
select name,age3
from #temp
where age3>=90
union all
select name,age4
from #temp
where age4>=90
union all
select name,age5
from #temp
where age5>=90
union all
select name,age6
from #temp
where age6>=90
) aa
group by aa.name
) b
where a.name*=b.name
) ccc
where aaa.name=bbb.name
and bbb.name=ccc.name |
|