Извините за поздний ответ.
Вот решение.Я надеюсь, что это полезно для вас, мой друг:))
--Create a sample data
create table temp
(
shopid int,
transactionId int,
articleId int,
)
create table yt
(
shopid int,
transactionId int,
article int,
articleCount int
)
insert into temp values (100, 8797, 4711)
insert into temp values (100, 8797, 3572)
insert into temp values (100, 8797, 3572)
insert into temp values (100, 8797, 3001)
insert into yt
select shopid, transactionId, articleId, count(articleId) as articleCount
from temp
group by shopid, transactionId, articleId
------
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(c.col+cast(rn as varchar(10)))
from
(
select row_number() over(partition by shopid
order by shopid, article) rn
from yt
) d
cross apply
(
select 'article' col, 1 sort union all select 'articleCount', 2
) c
group by col, rn, sort
order by rn, sort
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
print @cols
set @query = 'SELECT shopid, ' + @cols + '
from
(
select shopid,
col+cast(rn as varchar(10)) col,
value
from
(
-- when you perform an unpivot the datatypes have to be the same.
-- you might have to cast the datatypes in this query
select shopid, article, cast(articleCount as int) as articleCount,
row_number() over(partition by shopid order by shopid, article) rn
from yt
) src
unpivot
(
value
for col in (article, articleCount)
) unpiv
) d
pivot
(
max(value)
for col in (' + @cols + ')
) p '
execute(@query);
---Delete table
drop table temp
drop table yt