I think I've found a solution without cursors.
I Haven't SQL server at the moment, but if anyone can test it
--variables
declare @rank char(3),@maxRank char(3),@SQLcreateTable2 nvarchar(1000)
--calculation of maximum number of prices (maxRank)
select @maxRank=max(idcount) from
(select id, count(*) as idcount
from table1
group by id) as testtable
--create a work table to set the 'rank' of the price for one item on asc order
create table workTable1
(
id nvarchar(5),
rank char(3),
price money
)
select into workTable1
id,0,price
from table1
--create Table2 which is the final table, with the correct number of price columns (maxRank)
set @rank=1
select @SQLcreateTable2 = N'create table dbo.Table2(id nvarchar(5), '
while (@rank< @maxRank)
begin
select @SQLcreateTable2 = @SQLcreateTable2 + 'price_'+ltrim(rtrim(@rank))+' money,'
select @rank= @rank+ 1
end
if @rank= @maxRank
begin
select @SQLcreateTable2 = @SQLcreateTable2 + 'price_'+ltrim(rtrim(@maxRank))+' money)'
end
Exec @SQLcreateTable2
--make a loop to insert the lower price for each itm, the the second one,... then the last one
set @rank=1
while (@rank<=@maxrank))
begin
--select each item with its minimum price, insert this price in the price_1 column then ...
EXEC 'update table2
set price_' +ltrim(rtrim(@rank))+ ' = t.price
from
(workTable1 t
inner join
(select
id,min(price) as minPrice
from
workTable1 t1
where rank=0) as tableMin
on t.id=tableMin.id and t.price=tableMin.minPrice)'
end
--Do the trick update the workTable1, the goal is to have on the next loop not the first lower price but the second one and so on ...
UPDATE workTable1
SET workTable1.rank = @rank
from
(workTable1 t
inner join
(select
id,min(price) as minPrice
from
workTable1 t1
where num=0) as tableMin
on t.id=tableMin.id and t.price=tableMin.minPrice)
this is the END
end
--------------------------------------------------
[highlight]
Django[/highlight]
bug exterminator
tips'n tricks addict