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

交叉表,看了一些例子还是搞不出来!
表:
type_config     type_config1     money
        1                           人民币           20
        1                               港币           20
        2                           人民币           50
        1                               港币           20
        2                           人民币           20
        1                                 港币         20
        2                                 港币         20
        1                           人民币           20


输出


type_config1         1               2
人民币                     XX1           XX2
港币                         XX1           XX2

说明:
XX1为人民币type_config为1的汇总
XX2为港币type_config为2的汇总

type_config1有很多币类型

帮帮我,我搞了一天了..头大..




------解决方案--------------------
--创建测试环境
create table #t(type_config int,type_config1 varchar(20),[money] int)

--插入测试数据
insert #t(type_config,type_config1,[money])
select '1 ', '人民币 ', '20 ' union all
select '1 ', '港币 ', '20 ' union all
select '2 ', '人民币 ', '50 ' union all
select '1 ', '港币 ', '20 ' union all
select '2 ', '人民币 ', '20 ' union all
select '1 ', '港币 ', '20 ' union all
select '2 ', '港币 ', '20 ' union all
select '1 ', '人民币 ', '20 '

--求解过程
declare @sql varchar(8000)
set @sql= 'select type_config1 '
select @sql = @sql + ',sum(case type_config when ' + convert(varchar(20),type_config) + ' then money else 0 end) as [ ' + convert(varchar(20),type_config) + '] '
from (select distinct type_config from #t) _x
select @sql = @sql + ' from #t group by type_config1 '

exec( @sql)

--删除测试环境
drop table #t

/*--测试结果
type_config1 1 2
-------------------- ----------- -----------
港币 60 20
人民币 40 70
*/


------解决方案--------------------
create table t
(type_config int,
type_config1 varchar(20),
[money] money
)
insert into t