将许多数据集按行计成多行和多列(T-SQL)

时间:2019-07-05 09:33:03

标签: sql-server tsql

这是我的sql语句的结果:

   shopId  transactionId  articleId
   100     8797           4711
   100     8797           3572
   100     8797           3572
   100     8797           3001

我需要将transactionId的行合并为一行。另外,我需要为每篇文章“创建”一个新列,例如:

   shopId  transactionId  article1 article1Count article2 article2Count article3 article3Count 
   100     8797           4711     1             3572     2             3001     1

使用T-SQL动态执行此任务的正确方法是什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

对不起,您的回复很晚。

这是一个解决方案。我希望对您有用,我的朋友:))

--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