如何透视这些内容?

时间:2019-05-14 06:51:11

标签: sql-server pivot-table

我该如何对结果内容进行PIVOT?我当前的查询有什么问题,因为它返回null?

select 'ClientResponse' As Item,
[0],[1],[2],[3],[4],[5],[6],[7]
FROM (
SELECT ClientID, ClientResponse   
FROM TestResponses where ClientID = 116 and TestID = 16) As SourceTable  
PIVOT  
(  
 MAX(ClientResponse)  
 FOR ClientID IN ([0], [1], [2], [3], [4],[5],[6],[7])  
) AS PivotTable; 

我的源表在哪里

enter image description here

我的代码段像这样返回 enter image description here

3 个答案:

答案 0 :(得分:1)

嗨,如果我了解您的尝试,我认为这些示例可以为您提供帮助:

CREATE TABLE #ClientResponse (ClientId int, ClientResponse varchar(50))

INSERT INTO #ClientResponse
SELECT 116,'M'
UNION ALL 
SELECT 116,'M'
UNION ALL 
SELECT 116,'N'
UNION ALL 
SELECT 116,'J'
UNION ALL 
SELECT 116,'G'
UNION ALL 
SELECT 116,'M'
UNION ALL 
SELECT 116,'K'




select 'ClientResponse' As Item,
[0],[1],[2],[3],[4],[5],[6],[7]
FROM (SELECT *, ROW_NUMBER() OVER(ORDER by ClientId) AS 'IndexResponse' FROM #ClientResponse) As SourceTable  
PIVOT  
(  
 MAX(ClientResponse)  
 FOR IndexResponse IN ([0], [1], [2], [3], [4],[5],[6],[7])  
) AS PivotTable; 


DROP TABLE #ClientResponse

结果:

enter image description here

答案 1 :(得分:1)

ClientID的值与枢轴([0], [1], ...)的列名不匹配。

但是您可以使用以下命令,并使用DENSE_RANK创建一个组号(从1开始):

SELECT 'ClientResponse' AS Item, [1],[2], [3], [4], [5], [6], [7]
FROM (
    SELECT ClientResponse, 
        DENSE_RANK() OVER (ORDER BY ClientID ASC) AS groupNum
    FROM TestResponses
    WHERE ClientID = 116 AND TestID = 16
) AS st PIVOT (  
    MAX(ClientResponse)  
    FOR groupNum IN ([1],[2], [3], [4], [5], [6], [7])  
) AS pt; 

demo on dbfiddle.uk

答案 2 :(得分:1)

declare @maxColumnCount int=0;
declare @Query varchar(max)='';
declare @DynamicColumnName nvarchar(MAX)='';

-- table type variable that store all values of column row no
DECLARE @TotalRows TABLE( row_count int)
INSERT INTO @TotalRows (row_count)
SELECT (ROW_NUMBER() OVER(PARTITION BY ClientID order by TestResponseID asc)) as 
row_no FROM TestResponses where ClientID = 116 and TestID = 16

-- Get the MAX value from @TotalRows table
set @maxColumnCount= (select max(row_count) from @TotalRows)
select * from @TotalRows 
-- loop to create Dynamic max/case and store it into local variable 
DECLARE @cnt INT = 1;
 WHILE @cnt <= @maxColumnCount
   BEGIN
      set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= 
 '+cast(@cnt 
   as varchar)+' then ClientResponse end )as Item_'+cast(@cnt as varchar)+''
   SET @cnt = @cnt + 1;
END;

  -- Create dynamic CTE and store it into local variable @query 
  set @Query='
     with CTE_tbl as
     (
       SELECT ClientID,ClientResponse,
       ROW_NUMBER() OVER(PARTITION BY ClientID order by TestResponseID asc) as row_no
       FROM TestResponses where ClientID = 116 and TestID = 16
     )
 select
     ClientID
     '+@DynamicColumnName+'
    FROM CTE_tbl
    group By ClientID'
 --print @Query
-- Execute the Query
execute (@Query)