日期:2014-05-18  浏览次数:20548 次

有点难的查询
如表   t1
col1   col2   col3  
a           1       好      
a           1       好
a           2       不好
a           2       不好
b           2       不好
b           2       不好
b           1       好
b           1       好
b           3         好
b           3       好

结果是:
col1   汇总1     汇总1状态     汇总2     汇总2状态     汇总3       汇总3状态
a           2               好                 4                 不好           0                 好
b           4               不好             2                 好               6                 好

表就是这个结构.憋了两天没有出来.急切求助,望高手赐教!


------解决方案--------------------
看不明白你题目什么意思
------解决方案--------------------
整理下
如表 t1
col1 col2 col3
a 1 好
a 1 好
a 2 不好
a 2 不好
b 2 不好
b 2 不好
b 1 好
b 1 好
b 3 好
b 3 好

结果是:
col1 汇总1 汇总1状态 汇总2 汇总2状态 汇总3 汇总3状态
a 2 好 4 不好 0 好
b 4 不好 2 好 6 好
------解决方案--------------------
create table tb(col1 varchar(10),col2 varchar(10),col3 varchar(10))
insert into tb values( 'a ', '1 ', '好 ' )
insert into tb values( 'a ', '1 ', '好 ')
insert into tb values( 'a ', '2 ', '不好 ')
insert into tb values( 'a ', '2 ', '不好 ')
insert into tb values( 'b ', '2 ', '不好 ')
insert into tb values( 'b ', '2 ', '不好 ')
insert into tb values( 'b ', '1 ', '好 ')
insert into tb values( 'b ', '1 ', '好 ')
insert into tb values( 'b ', '3 ', '好 ')
insert into tb values( 'b ', '3 ', '好 ')
go

--静态SQL
select col1 ,
sum(case when col2 = 1 and col3 = '好 ' then cnt else 0 end) '汇总1_好 ',
sum(case when col2 = 1 and col3 = '不好 ' then cnt else 0 end) '汇总1_不好 ',
sum(case when col2 = 2 and col3 = '好 ' then cnt else 0 end) '汇总2_好 ',
sum(case when col2 = 2 and col3 = '不好 ' then cnt else 0 end) '汇总2_不好 ',
sum(case when col2 = 3 and col3 = '好 ' then cnt else 0 end) '汇总3_好 ',
sum(case when col2 = 3 and col3 = '不好 ' then cnt else 0 end) '汇总3_不好 '
from
(
select col1,col2,col3,count(*) cnt from tb group by col1,col2,col3