0

我有两张这样的桌子

table1 按 paymentid、paydate 排序:

 paymentid   paydate   amount

  1         20120101    100

  1         20120101    150

  1         20120101    150

  2         20120115    100

  2         20120115    100

...

表2按paymentid、paydate排序:

paymentid    paydate   pay1   pay2   pay3....base on the position from table1...up to pay20

1            20120101   null  null    null   

2            20120115   null  null    null

...

更新后table2应该是这样的

1            20120101   100   100     150   null.....

2            20120115   100   100     null  null    null.....

到目前为止,我可以提出的可能解决方案是:

1,用于循环通过 table1 的临时表

2、游标……目前的解决办法:

declare @paymentid int 

declare @paydate   char(10)

declare @amount    money

declare @count int

declare @saveid int

declare @savedate char(10)

delcare cur cursor for select paymentid, paydate, amount from table1 order by paymentid, paydate

open cur



fetch next from cur into @paymentid,@paydate,@amount

while @@fetch_status = 0

  if @saveid <> @paymentid or @savedate <> @paydate

     set @count = 1

     set @saveid = @paymentid

     set @savedate = @paydate

  else set @count = @count + 1

  if @count = 1

  update table2 

  set pay1 = @amount

  where paymentid = @paymentid and paydate = @paydate

  if @count = 2

  update table2 

  set pay2 = @amount

  ...

  fetch next

  ...

任何建议将不胜感激。

4

1 回答 1

1

Try this

SQL Fiddle

declare @Test Table (paymentid int, 
                   paydate varchar(25), amount int)


INSERT INTO @Test

SELECT 1,'20120101',100
UNION ALL
SELECT 1,'20120101',150
UNION ALL
SELECT 1,'20120101',150
UNION ALL
SELECT 2,'20120115',100
UNION ALL
SELECT 2,'20120115',100

--INSERT into Table2 //insert here
SELECT * FROM (
SELECT *, 'pay' + CAST(Row_Number() OVER (Partition by paymentid, 
                        paydate order by amount) AS VARCHAR) PayCol
FROM @Test
)  V
PIVOT 
(
  MAX(Amount) For PayCol IN 
   (pay1,pay2,pay3,pay4, pay5, pay6, pay7, pay8, pay9, pay10,
        pay11,pay12,pay13,pay14, pay15, pay16, pay17, pay18, pay19, pay20)
) As P
于 2012-10-12T17:15:08.020 回答