SQL SERVER 2008 有点小复杂行转列,如图,谢谢
http://www.cnblogs.com/emmy/p/4308607.html
谢谢各位帮助。后来还是得自己琢磨了。先用xml path 合并行,然后对行字段进行截取,终于搞定了,供大家参考
--创建字符分割函数,脚本来自网络
IF NOT OBJECT_ID('f_GetStr') IS NULL
DROP FUNCTION [f_GetStr]
GO
--分段截取函数
CREATE FUNCTION dbo.f_GetStr(
@s varchar(8000), --包含多个数据项的字符串
@pos int, --要获取的数据项的位置
@split varchar(10) --数据分隔符
)RETURNS varchar(1000)
AS
BEGIN
IF @s IS NULL RETURN(NULL)
DECLARE @splitlen int
SELECT @splitlen=LEN(@split+'a')-2
WHILE @pos>1 AND CHARINDEX(@split,@s+@split)>0
SELECT @pos=@pos-1,
@s=STUFF(@s,1,CHARINDEX(@split,@s+@split)+@splitlen,'')
RETURN(ISNULL(LEFT(@s,CHARINDEX(@split,@s+@split)-1),''))
END
GO
--对大视图进行查询截取等操作
select
*,
b.付款金额1+b.付款金额2+b.付款金额3+b.付款金额4+b.付款金额5+b.付款金额6+b.付款金额7+b.付款金额8+b.付款金额9 付款合计
from(
select
a.合同编号,
dbo.f_GetStr(a.付款信息,1,',') 付款日期1,
cast((case when dbo.f_GetStr(a.付款信息,2,',') <>'' then dbo.f_GetStr(a.付款信息,2,',') else 0 end) as decimal(18,2)) 付款金额1,
dbo.f_GetStr(a.付款信息,3,',') 付款日期2,
cast((case when dbo.f_GetStr(a.付款信息,4,',') <>'' then dbo.f_GetStr(a.付款信息,4,',') else 0 end) as decimal(18,2)) 付款金额2,
dbo.f_GetStr(a.付款信息,5,',') 付款日期3,
cast((case when dbo.f_GetStr(a.付款信息,6,',') <>'' then dbo.f_GetStr(a.付款信息,6,',') else 0 end) as decimal(18,2)) 付款金额3,
dbo.f_GetStr(a.付款信息,7,',') 付款日期4,
cast((case when dbo.f_GetStr(a.付款信息,8,',') <>'' then dbo.f_GetStr(a.付款信息,8,',') else 0 end) as decimal(18,2)) 付款金额4,
dbo.f_GetStr(a.付款信息,9,',') 付款日期5,
cast((case when dbo.f_GetStr(a.付款信息,10,',') <>'' then dbo.f_GetStr(a.付款信息,10,',') else 0 end) as decimal(18,2)) 付款金额5,
dbo.f_GetStr(a.付款信息,11,',') 付款日期6,
cast((case when dbo.f_GetStr(a.付款信息,12,',') <>'' then dbo.f_GetStr(a.付款信息,12,',') else 0 end) as decimal(18,2)) 付款金额6,
dbo.f_GetStr(a.付款信息,13,',') 付款日期7,
cast((case when dbo.f_GetStr(a.付款信息,14,',') <>'' then dbo.f_GetStr(a.付款信息,14,',') else 0 end) as decimal(18,2)) 付款金额7,
dbo.f_GetStr(a.付款信息,15,',') 付款日期8,
cast((case when dbo.f_GetStr(a.付款信息,16,',') <>'' then dbo.f_GetStr(a.付款信息,16,',') else 0 end) as decimal(18,2)) 付款金额8,
dbo.f_GetStr(a.付款信息,17,',') 付款日期9,
cast((case when dbo.f_GetStr(a.付款信息,18,',') <>'' then dbo.f_GetStr(a.付款信息,18,',') else 0 end) as decimal(18,2)) 付款金额9
from (
select
合同编号,
(select 付款日期+',',str(付款金额)+',' from ZZGNCGHTSJ2_VIEW_ALL where 合同编号=A.合同编号 for xml path('')) 付款信息
from ZZGNCGHTSJ2_VIEW_ALL A
group by 合同编号
) a
) b
主要是这个付款日期,不知道如何安放上去
谢谢楼上朋友,有点类似但不一样,首先我的列是固定的,就分7次付款,其次我的日期是不固定的,我希望按照付款的序号,第一次付款放在付款日期1和付款金额1,第二次付款放在付款日期2和付款金额2...,以此类推
7个查询,每个查询都对应一个编号并取别名付款日期*和付款金额*然后再根据合同编号进行左关联应该就出来了吧
7个查询,每个查询都对应一个编号并取别名付款日期*和付款金额*然后再根据合同编号进行左关联应该就出来了吧