枢轴获取多个记录

时间:2018-11-16 05:53:39

标签: sql-server

我正在研究数据透视功能。 我有2个表,一个是userinfo,另一个是爱好。 我的桌子将如下图所示。 Table Image 我将用逗号分隔的数据保存到userinfo中。 我希望所有以逗号分隔的爱好及其各自的列名。 我尝试过,但是获取每个爱好的个人记录,而不是单行 如下图所示。 Output currently 我的代码如下:

DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)
--drop table Temptbl1
--drop table Temptbl2
 IF EXISTS (SELECT * FROM Temptbl1)
drop table Temptbl1
IF EXISTS (SELECT * FROM Temptbl2)
drop table Temptbl2
SELECT * INTO Temptbl1 FROM UserInfo CROSS APPLY dbo.SplitData(Hobbies,',')
--select * from Temptbl1
Select * into Temptbl2 from Temptbl1 s,Hobbies h where s.DividedItem=h.Hid
--select * from Temptbl2
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(HName) from Hobbies 
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')
    print @cols
set @query = 'SELECT distinct UId,UName,UAge,Hid, '+@cols +'  from ( select 
* from Temptbl2 )
          x
          pivot 
         (max(DividedItem) for HName in (' + @cols + ') ) p '
select * from Temptbl2
exec(@query)

1 个答案:

答案 0 :(得分:0)

您正在从temptbl2中选择所有列,并且不需要它们。 Hid列在此处被选中,这使行成为唯一,并且枢轴fails使行正确地聚集了结果。只需将其更改为此:

set @query = 'SELECT distinct UId,UName,UAge, '+@cols +'  from ( select  UId,UName,UAge, DividedItem, HName 
 from Temptbl2 )
          x
          pivot 
         (max(DividedItem) for HName in (' + @cols + ') ) p '

您会没事的。


这里是SQL Server 2016 SP1上的完整示例。我正在使用string_split拆分数据和临时表来存储它。另外,稍微更改联接语法(您已过时,不应使用)。您可以修改以下代码以轻松地在您的环境中工作:

DECLARE @hobbies TABLE
(
    [HiD] INT
   ,[HName] VARCHAR(12)
);

INSERT INTO @hobbies ([HiD], [HName])
VALUES (1, 'Reading')
      ,(2, 'Singing')
      ,(3, 'Dancing');

DECLARE @UserInfo TABLE
(
    [UID] INT
   ,[UName] VARCHAR(12)
   ,[UAddress] VARCHAR(12)
   ,[UAge] TINYINT
   ,[Hobbies] VARCHAR(12)
)

INSERT INTO @UserInfo ([UID], [UName], [UAddress], [UAge], [Hobbies])
VALUES (1, 'Abc', 'addr1', 25, '2,3')
      ,(2, 'Def', 'addr2', 27, '1,2,3')
      ,(3, 'Ghi', 'addr3', 20, '1');

DROP TABLE IF EXISTS #TEST;

SELECT *
INTO #TEST
FROM @UserInfo UI
CROSS APPLY string_split(UI.[Hobbies], ',') HS
INNER JOIN @hobbies H
    ON HS.[value] = h.[HiD]

DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);

Select @cols = STUFF((SELECT distinct ',' + QUOTENAME(HName) from @hobbies 
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')

set @query = 'SELECT distinct UId,UName,UAge, '+@cols +'  from ( select  uid, uname, uage, hname, value
 from #TEST )
          x
          pivot 
         (max(value) for HName in (' + @cols + ') ) p '

exec(@query)

enter image description here