创建表,数据
createtabletest(合同编号varchar(10),
付款日期varchar(10),
付款金额int,
序号varchar(2))
insertintotestvalues('JNHS1501','2015-01-01',2600000,1)
insertintotestvalues('JNHS1501','2015-04-01',1000000,2)
insertintotestvalues('JNHS1501','2015-04-27',2000000,3)
insertintotestvalues('JNHS1501','2015-04-16',1500000,4)
insertintotestvalues('JNHS1501','2015-05-26',2000000,5)
insertintotestvalues('JNHS1501','2015-06-16',2000000,6)
insertintotestvalues('JNHS1501','2015-07-29',684770,7)
insertintotestvalues('JNHS1502','2015-05-05',180000,1)
insertintotestvalues('JNHS1502','2015-01-05',50000,2)
执行
declare@sqlvarchar(4000)set@sql='select合同编号'
select@sql=@sql+',max(case序号when'''+[序号]+'''then[付款日期]end)as
付款日期'+序号+',max(case序号when'''+[序号]+'''then[付款金额]end)as
付款金额'+序号+''
from(selectdistinct序号fromtest)asa
select@sql=@sql+'fromtestgroupby合同编号'
exec(@sql)
结果: