sql的一个纠结问题
两个表 结构都是一样 数据不同
A
id num class
1 10 类别1
1 101 类别2
...
2 20 类别1
...
B
id num class
1 100 类别1
1 1001 类别2
1 1000 类别3
...
2 20 类别1
...
能不能列转行 得到下面的结果
id 类别1 类别2 类别3 ...(A/B中的全部类别)
1 (A的num,B的num) (A的num,B的num)...
.....
如果A/B中没有对应类别的num 就为0,得到的结果数是A表和B表的ID合集
其中 A和B中的id 不一定完全相同,可能A中的id在b中就没有,反之亦然。且两表中,同id的类别也不一定相同,例如A中id为1的可能就两个类别有数据,但是B中可能id为1的有两个以上的分类数据
这个需求,我感觉sql应该可以实现的,求帮助
[解决办法]
未行转列之前把符合的数据筛选出来,放入临时表,然后再用动态行转列的例子去做。
[解决办法]
先给两表连接起来,然后再列转行
[解决办法]
已经给出思路了 筛选你要的结果放到临时表里然后经典行列转换。
http://blog.csdn.net/szstephenzhou/article/details/7091819
[解决办法]
--> 测试数据:[A1]goif object_id('[A1]') is not null drop table [A1]gocreate table [A1]([id] int,[num] int,[class] varchar(5))goinsert [A1]select 1,10,'类别1' union allselect 1,101,'类别2' union allselect 2,20,'类别1' union allselect 2,50,'类别1'--> 测试数据:[B1]goif object_id('[B1]') is not null drop table [B1]create table [B1]([id] int,[num] int,[class] varchar(5))goinsert [B1]select 1,100,'类别1' union allselect 1,1001,'类别2' union allselect 1,1000,'类别3' union allselect 2,20,'类别1' union allselect 2,20,'类别2'gocreate table #t(id int,numa int,numb int,class varchar(5))insert #tselect b.id,sum(isnull(a.num,0)) as numa,sum(isnull(b.num,0)) as numb,b.classfrom [B1] b left join [A1] aon b.id=a.id group by b.id,b.classselect * from #tdeclare @str varchar(1000)set @str=''select @str=@str+','+class+'=sum(case when class=' +QUOTENAME(class,'''')+'then numa+numb else 0 end)'from #t group by classset @str='select id'+@str+' from #t group by id'exec(@str)----------------------------------id 类别1 类别2 类别31 311 2113 21112 110 110 0