Мне потребовалось некоторое время, чтобы получить те же результаты, что и ожидаемый результат, но мне все-таки удалось все исправить:
if exists (select 1 from sysobjects where name = 'TempTable')
drop table TempTable;
if exists (select 1 from sysobjects where name = 'TempTable2')
drop table TempTable2;
declare @cols nvarchar(max)
, @cols2 nvarchar(max)
, @sql nvarchar(max)
, @loop int;
create table TempTable (id int primary key identity, CustomerID int, OrderID int, OrderPosition int, ArticleNumber int)
insert into TempTable (CustomerID, OrderID, OrderPosition, ArticleNumber) values (101,1,1,123)
insert into TempTable (CustomerID, OrderID, OrderPosition, ArticleNumber) values (101,1,2,799)
insert into TempTable (CustomerID, OrderID, OrderPosition, ArticleNumber) values (102,2,1,111)
insert into TempTable (CustomerID, OrderID, OrderPosition, ArticleNumber) values (103,3,1,456)
insert into TempTable (CustomerID, OrderID, OrderPosition, ArticleNumber) values (101,4,1,789)
insert into TempTable (CustomerID, OrderID, OrderPosition, ArticleNumber) values (103,5,1,444)
insert into TempTable (CustomerID, OrderID, OrderPosition, ArticleNumber) values (103,5,2,999)
insert into TempTable (CustomerID, OrderID, OrderPosition, ArticleNumber) values (101,6,1,555)
insert into TempTable (CustomerID, OrderID, OrderPosition, ArticleNumber) values (101,6,2,777)
insert into TempTable (CustomerID, OrderID, OrderPosition, ArticleNumber) values (101,6,3,222);
create table TempTable2 (CustomerID int, OrderID int, OrderPosition int, ArticleNumber int, ArticleDesc varchar(100))
select @loop = min(id) from TempTable
while @loop is not null
begin
set @sql = ' insert into TempTable2 (CustomerID, OrderID, OrderPosition, ArticleNumber, ArticleDesc)
select top 4 CustomerID, OrderID, OrderPosition, ArticleNumber, ''ArticleNumber ''+cast(rank() over (order by orderID desc, OrderPosition)as varchar)
from TempTable where CustomerID = '+cast((select CustomerID from TempTable where id = @loop) as varchar)+
'order by orderID desc, OrderPosition'
exec (@sql)
select @loop = min(id) from TempTable where id > @loop
end
select
CustomerID
, sum(isnull([ArticleNumber 1],0)) [ArticleNumber 1]
, sum(isnull([ArticleNumber 2],0)) [ArticleNumber 2]
, sum(isnull([ArticleNumber 3],0)) [ArticleNumber 3]
, sum(isnull([ArticleNumber 4],0)) [ArticleNumber 4]
from
(
select
CustomerID, OrderID, OrderPosition, ArticleDesc, ArticleNumber
from TempTable2
group by CustomerID, OrderID, OrderPosition, ArticleDesc, ArticleNumber
) d
pivot
(sum(ArticleNumber) for ArticleDesc in ([ArticleNumber 1],[ArticleNumber 2],[ArticleNumber 3],[ArticleNumber 4])
) p
group by CustomerID
Мой ответ может быть не самым лучшим, поскольку гениальные парни ответили выше, но я все равно получаю те же результаты ...