我在旋转多个列时需要帮助我的查询,基本上,我只需要一个简单的查询,我无法理解它,希望有人可以帮助我。
非透视:
MTH ID TEAM Metric_ID Score Outcome_Score
1/10/2016 abc11 teamA ID_1 292 3
1/11/2016 abc11 teamA ID_1 300 0
1/10/2016 abc11 teamA ID_10 100 0
1/11/2016 abc11 teamA ID_10 84 0
1/10/2016 abc11 teamA ID_11 11% 0
1/11/2016 abc11 teamA ID_11 12% 0
待:
LANID TEAM Metric_ID Oct_Score Oct_Outcome_Score Nov_Score Nov_Outcome_Score
abc11 teamA ID_1 292 3 300 0
abc11 teamA ID_10 100 0 84 0
abc11 teamA ID_11 11% 0 12% 0
我已经在下面提出了,但每次我为结果添加字段时,它都会完全混淆查询。实际查询更复杂。我只是需要想法。感谢。
SELECT ID AS LANID, Team, Metric_ID
, CONVERT(varchar(3), MTH, 100) SMTH
, Oct_Score
, Oct_Outcome_Score
, Nov_Score
, Nov_Outcome_Score
FROM TableA
PIVOT
(
SUM(Score)
FOR SMTH IN (Oct_Score, Nov_Score)
) AS P
答案 0 :(得分:1)
这应该有效:
WITH Src AS
(
SELECT * FROM (VALUES
('1/10/2016', 'abc11', 'teamA', 'ID_1 ', 292, 3),
('1/11/2016', 'abc11', 'teamA', 'ID_1 ', 300, 0),
('1/10/2016', 'abc11', 'teamA', 'ID_10', 100, 0),
('1/11/2016', 'abc11', 'teamA', 'ID_10', 84, 0),
('1/10/2016', 'abc11', 'teamA', 'ID_11', 11, 0),
('1/11/2016', 'abc11', 'teamA', 'ID_11', 12, 0)
)T(MTH, ID, TEAM, Metric_ID, Score, Outcome_Score)
)
SELECT * FROM
(
SELECT ID, TEAM, Metric_ID, Value,
CASE WHEN DATEPART(M, MTH)=10 THEN 'Oct_'
WHEN DATEPART(M, MTH)=11 THEN 'Nov_' END+Col ToPivot
FROM
(SELECT CONVERT(date, MTH, 103) MTH, ID, TEAM, Metric_ID, Score, Outcome_Score FROM Src) T1
UNPIVOT (Value FOR Col IN (Score, Outcome_Score)) U1
) T
PIVOT (SUM(Value) FOR ToPivot IN (Oct_Score, Oct_Outcome_Score, Nov_Score, Nov_Outcome_Score)) P
<强>结果:强>
ID TEAM Metric_ID Oct_Score Oct_Outcome_Score Nov_Score Nov_Outcome_Score
----- ----- --------- ----------- ----------------- ----------- -----------
abc11 teamA ID_1 292 3 300 0
abc11 teamA ID_10 100 0 84 0
abc11 teamA ID_11 11 0 12 0
答案 1 :(得分:1)
要动态数据透视表,您可以使用以下查询(动态数据透视表列名称将不按正确顺序)
CREATE Table #Item(id varchar(250),team varchar(250),Metric_ID varchar(20),col varchar(250),Score int)
;WITH Src AS(SELECT * FROM (VALUES ('10/1/2016', 'abc11', 'teamA', 'ID_1 ', 292, 3),('11/1/2016', 'abc11', 'teamA', 'ID_1 ', 300, 0),('10/1/2016', 'abc11', 'teamA', 'ID_10', 100, 0),('11/1/2016', 'abc11', 'teamA', 'ID_10', 84, 0),('10/1/2016', 'abc11', 'teamA', 'ID_11', 11, 0),('11/1/2016', 'abc11', 'teamA', 'ID_11', 12, 0))T(MTH,ID, TEAM, Metric_ID, Score, Outcome_Score))
INSERT INTO #Item
select ID,TEAM,Metric_ID,DateName(M, DateAdd(M, MONTH(MTH), -1))+'_Score',Score from Src
UNION ALL
select ID,TEAM,Metric_ID,DateName(M, DateAdd(M, MONTH(MTH), -1))+'_Outcome_Score',Outcome_Score from Src
DECLARE @Query AS NVARCHAR(MAX) DECLARE @ColumnName AS NVARCHAR(MAX)
SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(col)
FROM (SELECT DISTINCT col FROM #Item) AS ColName
SET @Query = N'SELECT ID,TEAM,Metric_ID ,' + @ColumnName + 'FROM #Item PIVOT(SUM(Score) FOR col IN (' + @ColumnName + ')) AS PVTTable'
EXEC sp_executesql @Query
Drop table #Item
答案 2 :(得分:0)
最后,这个问题得到了解决。 缺少原因&#34; GROUP BY&#34;因此,根据旋转列的数量,数据加倍/三倍。