您的位置:首页 > 数据库

按条件分类汇总sql脚本例子

2007-11-29 16:17 1341 查看
------按条件分类汇总sql脚本例子
select 上级部门,部门名称,姓名,
sum(case when NumType='4' then 1 else 0 end ) 新装 ,
sum(case when NumType='7' then 1 else 0 end ) 续费,
sum(case when NumType='82' then 1 else 0 end ) e8--(含单独办理e8)
from viewall --揽装视图,其实质内容为number与部门信息的映射 
where statTime>='20070101'
and statTime<='20071031'
group by 上级部门,部门名称,姓名 --按字段(或字段组合)分类汇总
order by 上级部门,部门名称,姓名 --按顺序排序,如果按倒序排序 在字段后加 desc

---效果等同于下面的语句组合,下面的语句组合也是常用的

------begin---------------------------------
select 上级部门,部门名称,姓名,
sum(case when NumType='4' then 1 else 0 end ) 新装
into #t1
from viewall
where statTime>='20070101'
and statTime<='20071031'
group by 上级部门,部门名称,姓名
order by 上级部门,部门名称,姓名

select 上级部门,部门名称,姓名,
sum(case when NumType='7' then 1 else 0 end ) 续费
into #t2
from viewall
where statTime>='20070101'
and statTime<='20071031'
group by 上级部门,部门名称,姓名
order by 上级部门,部门名称,姓名

select 上级部门,部门名称,姓名,
sum(case when NumType='82' then 1 else 0 end ) e8
into #t3
from viewall
where statTime>='20070101'
and statTime<='20071031'
group by 上级部门,部门名称,姓名
order by 上级部门,部门名称,姓名

select 上级部门,部门名称,姓名 into #t4 from #t1
union select 上级部门,部门名称,姓名 from #t2
union select 上级部门,部门名称,姓名 from #t3

select a.*,b.新装 into #t5 from #t4 a left join #t1 b on a.姓名=b.姓名 and a.部门名称=b.部门名称
select a.*,b.续费 into #t6 from #t5 a left join #t2 b on a.姓名=b.姓名 and a.部门名称=b.部门名称
select a.*,b.e8 into #t7 from #t6 a left join #t3 b on a.姓名=b.姓名 and a.部门名称=b.部门名称

select * from #t7

-------end----------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: