在SQL Server中透视varchar列?

时间:2019-06-11 05:48:29

标签: sql sql-server

enter image description here

我试图将一些结果放入数据透视表中,但未获得预期的结果。在这里,我已将代码和结果放入

DECLARE @TblIdeaCategory TABLE 
(
IdeaImplement varchar(2000),
IdeaCategory varchar(2000)
)

INSERT INTO @TblIdeaCategory values('Metrics Feedback One  #1','MetricFeedback')
INSERT INTO @TblIdeaCategory values('Metrics Feedback Two #1','MetricFeedback')
INSERT INTO @TblIdeaCategory values('Analysis Feedback One #1','AnalysisFeedback')
INSERT INTO @TblIdeaCategory values('Analysis Feedback Two #1','AnalysisFeedback')
INSERT INTO @TblIdeaCategory values('Idea Generation Feedback One #1','IdeaGenerationFeedback')
INSERT INTO @TblIdeaCategory values('Idea Generation Feedback Two #1','IdeaGenerationFeedback')


select 
 IdeaGenerationFeedback,AnalysisFeedback,MetricFeedback from 

(select IdeaImplement,IdeaCategory
 from  @TblIdeaCategory as board
 ) resultTable
pivot (
 max(IdeaImplement)  for IdeaCategory in (IdeaGenerationFeedback,AnalysisFeedback,MetricFeedback))  as resultpivot


 select  IdeaImplement,IdeaCategory from @TblIdeaCategory

2 个答案:

答案 0 :(得分:1)

以下查询应执行您想要的操作:

DECLARE @TblIdeaCategory TABLE 
(
IdeaImplement varchar(2000),
IdeaCategory varchar(2000)
)

INSERT INTO @TblIdeaCategory values('Metrics Feedback One  #1','MetricFeedback')
INSERT INTO @TblIdeaCategory values('Metrics Feedback Two #1','MetricFeedback')
INSERT INTO @TblIdeaCategory values('Analysis Feedback One #1','AnalysisFeedback')
INSERT INTO @TblIdeaCategory values('Analysis Feedback Two #1','AnalysisFeedback')
INSERT INTO @TblIdeaCategory values('Idea Generation Feedback One #1','IdeaGenerationFeedback')
INSERT INTO @TblIdeaCategory values('Idea Generation Feedback Two #1','IdeaGenerationFeedback')


select 
 IdeaGenerationFeedback,AnalysisFeedback,MetricFeedback from 

(select IdeaImplement,IdeaCategory,ROW_NUMBER() OVER(PARTITION BY IdeaCategory ORDER BY (SELECT 1)) AS RNO
 from  @TblIdeaCategory as board
 ) resultTable
pivot (
MAX(IdeaImplement)  for IdeaCategory in (IdeaGenerationFeedback,AnalysisFeedback,MetricFeedback))  as resultpivot

结果如下,

IdeaGenerationFeedback            AnalysisFeedback           MetricFeedback
Idea Generation Feedback One #1   Analysis Feedback One #1   Metrics Feedback One #1
Idea Generation Feedback Two #1   Analysis Feedback Two #1   Metrics Feedback Two #1

答案 1 :(得分:0)

我认为您实际上想在这里使用UNPIVOT而不是PIVOT,但是在任何情况下,您都可以使用一系列的并集,无论如何它们都可能会更好。

SELECT IdeaGenerationFeedback AS IdeaImplement, 'IdeaGenerationFeedback' AS IdeaCategory
FROM yourOriginalTable
UNION ALL
SELECT AnalysisFeedback, 'AnalysisFeedback' FROM yourOriginalTable
UNION ALL
SELECT MetricFeedback, 'MetricFeedback' FROM yourOriginalTable;