关于交插表的小问题,求助一下下。。。
表A
P_CD,M_A 二个字段
表B
USER_CD,RIQI,P_CD三个字段
二个表的结合条件是 表A.P_CD = 表B.P_CD
-------------------------------------------------------
如何得到:
RIQI1,RIQI2,RIQI3......
USER_CD1 M_A1 M_A2 M_A3 ......
USER_CD2 M_A1 M_A2 M_A3 ......
USER_CD3 M_A1 M_A2 M_A3 ......
. . . .
. . . .
. . . .
感谢!
------解决方案----------------------生成一个临时表
select b.user_cd,b.riqi,a.m_a into tmp from a,b where a.p_cd=b.p_cd
--动态SQL
declare @sql varchar(8000)
set @sql = 'select user_cd '
select @sql = @sql + ' , max(case px when ' ' ' + cast(px as varchar) + ' ' ' then m_a end) [riqi ' + cast(px as varchar) + '] '
from (select distinct px from (select px=(select count(1) from tmp where user_cd=t.user_cd and riqi <t.riqi)+1 , * from tmp t) m) as a
set @sql = @sql + ' from (select px=(select count(1) from tmp where user_cd=t.user_cd and riqi <t.riqi)+1 , * from tmp t) m group by user_cd '
exec(@sql)