星期六

一条经典的汇总的sql

表结构:
时间  地名    环境情况
1        北京     优秀
2        北京      良好
3        北京      差
4        天津     良好
5        天津     良好
6        上海      差

要求得到的结果:
地点  优秀   良好   差
北京   1       1         1
天津   2       0         0
上海   0       0         1



create table t([date] int identity(1,1),place nvarchar(10),circumstance nvarchar(10))
insert t select N'北京',N'优秀'
union all select N'北京',N'良好'
union all select N'北京',N'差'
union all select  N'天津',N'良好'
union all select N'天津',N'良好'
union all select N'上海',N'差'

select place [地点],
sum(case circumstance when N'优秀' then 1 else 0 end) [优秀],
sum(case circumstance when N'良好' then 1 else 0 end) [良好],
sum(case circumstance when N'差' then 1 else 0 end) [差]
from t
group by place

drop table t
/*
地点         优秀          良好          差          
---------- ----------- ----------- -----------
上海         0           0           1
天津         0           2           0
北京         1           1           1
*/




Select
uncd,
sum(case infoty when '1' then 1 else 0 end) as 早报,
sum(case infoty when '2' then 1 else 0 end) as 迟报,
sum(case infoty when '3' then 1 else 0 end) as 漏报,
sum(case infoty when '4' then 1 else 0 end) as 错报
From ST_INFSMRY_C
group by uncd

 

posted on 2006-06-02 13:32  星期六  阅读(1646)  评论(1编辑  收藏  举报