日期:2014-05-17  浏览次数:20447 次

sql的一个纠结问题
两个表 结构都是一样 数据不同

id num class
 1 10 类别1
 1 101 类别2
 ...
 2 20 类别1
 ...

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
------解决方案--------------------
SQL code

--> 测试数据:[A1]
go
if object_id('[A1]') is not null 
drop table [A1]
go
create table [A1](
[id] int,
[num] int,
[class] varchar(5)
)
go
insert [A1]
select 1,10,'类别1' union all
select 1,101,'类别2' union all
select 2,20,'类别1' union all
select 2,50,'类别1'

--> 测试数据:[B1]
go
if object_id('[B1]') is not null 
drop table [B1]
create table [B1](
[id] int,
[num] int,
[class] varchar(5)
)
go
insert [B1]
select 1,100,'类别1' union all
select 1,1001,'类别2' union all
select 1,1000,'类别3' union all
select 2,20,'类别1' union all
select 2,20,'类别2'

go
create table #t(
id int,
numa int,
numb int,
class varchar(5)
)
insert #t
select b.id,sum(isnull(a.num,0)) as numa,sum(isnull(b.num,0)) as numb,b.class
from [B1] b left join [A1] a
on b.id=a.id group by  b.id,b.class
select * from #t

declare @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 class
set @str='select id'+@str+' from #t group by id'
exec(@str)
----------------------------------
id    类别1    类别2    类别3
1    311    2113    2111
2    110    110    0