日期:2014-05-18 浏览次数:20740 次
select 调查结果, sum(case when 年龄段 when 'man' then 1 else 0 end) as '中年人', sum(case when 年龄段 when 'boy' then 1 else 0 end) as '小孩', sum(case when 年龄段 when 'old' then 1 else 0 end) as '老年人', count(1) as 总计 from tb group by 调查结果
------解决方案--------------------
declare @T table([调查结果] varchar(10),[man] int,[boy] int,[old] int) insert @T select '非常满意',10,50,45 union all select '满意',45,45,12 union all select '一般',21,21,21 union all select '不满意',2,2,3 union all select '非常不满意',0,0,0 select *,man+boy+old As 总计 from @T union all select '总计',sum([man]),sum([boy]), sum([old]),sum([man])+sum([boy])+sum([old]) from @T /* 调查结果 man boy old 总计 ---------- ----------- ----------- ----------- ----------- 非常满意 10 50 45 105 满意 45 45 12 102 一般 21 21 21 63 不满意 2 2 3 7 非常不满意 0 0 0 0 总计 78 118 81 277 */
------解决方案--------------------
要后面的汇总可以用with with t as ( select 调查结果, isnull(sum(case when 年龄类型 ='man' then 1 else 0 end),0) as '中年人', isnull(sum(case when 年龄类型 ='boy' then 1 else 0 end),0) as '小孩', isnull(sum(case when 年龄类型 ='old' then 1 else 0 end),0) as '老年人', count(1) as 总计 from tb a right join ( select 1 as 调查结果 union all select 2 as 调查结果 union all select 3 as 调查结果 union all select 4 as 调查结果 union all select 5 as 调查结果) b on b.调查结果=a.调查结果 group by b.调查结果 ), t1 as ( select '总计' as 调查结果,sum(中年人) as 中年人,sum(小孩) as 小孩, sum(老年人) as 老年人, sum(中年人)+sum(小孩)+sum(老年人) as 总计 from t ), t2 as ( select '满意度' as 调查结果,sum(case when 调查结果!='不满意' and 调查结果!='非常不满意' then 中年人 else 0 end)/sum(中年人) as 中年人,sum(case when 调查结果!='不满意' and 调查结果!='非常不满意' then 孩子 else 0 end)/sum(孩子) as 孩子,sum(case when 调查结果!='不满意' and 调查结果!='非常不满意' then 老年人 else 0 end)/sum(老年人) as 老年人,sum(case when 调查结果!='不满意' and 调查结果!='非常不满意' then 总计 else 0 end)/sum(总计) as 总计 from t ), t3 as ( select '不满意度' as 调查结果,sum(case when 调查结果='不满意' or 调查结果='非常不满意' then 中年人 else 0 end)/sum(中年人) as 中年人,sum(case when 调查结果='不满意' or 调查结果='非常不满意' then 孩子 else 0 end)/sum(孩子) as 孩子,sum(case when 调查结果='不满意' or 调查结果='非常不满意' then 老年人 else 0 end)/sum(老年人) as 老年人,sum(case when 调查结果='不满意' or 调查结果='非常不满意' then 总计 else 0 end)/sum(总计) as 总计 from t ) select * from t union all select * from t1 union all select * from t2 union all select * from t3 union all
------解决方案--------------------
create table test([id] int, [AgeLevel] varchar(10),[PROBLEM_ID] int) go insert test select 1,'老年人', 1 union all select 2,'小孩', 2 union all select 3,'老年人', 3 union all select 4,'中年人', 4 union all select 5,'老年人', 5 union all select 6,'老年人', 1 union all select 7,'小孩', 2 union all select 8,'小孩', 3 union all select 9,'中年人', 4 union all select 10,'中年人', 5 union all select 11,'老年人',2 select * from test declare @sql varchar(max) declare @sql2 varchar(100) declare @sql3 varchar(200) select @sql=isnull(@sql+',','')+' count(case when [AgeLevel]='''+[AgeLevel]+''' then [PROBLEM_ID] end) a