你可以UNPIVOT,然後轉動數據,它可能會表現得更好:
DECLARE @T TABLE
( VALUE_A INT, COUNT_A INT, VALUE_B INT, COUNT_B INT, VALUE_C INT, COUNT_C INT, VALUE_D INT, COUNT_D INT, VALUE_E INT,
COUNT_E INT, VALUE_F INT, COUNT_F INT, VALUE_G INT, COUNT_G INT, VALUE_H INT, COUNT_H INT, VALUE_I INT, COUNT_I INT
);
INSERT @T VALUES (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
WITH D AS
( SELECT Category = SUBSTRING(B, 7, LEN(B)), [Type] = 'Value', A
FROM @T
UNPIVOT
( A
FOR B IN ([VALUE_A], [VALUE_B], [VALUE_C], [VALUE_D], [VALUE_E], [VALUE_F], [VALUE_G], [VALUE_H], [VALUE_I])
) upvt
UNION ALL
SELECT Category = SUBSTRING(B, 7, LEN(B)), [Type] = 'Count', A
FROM @T
UNPIVOT
( A
FOR B IN ([COUNT_A], [COUNT_B], [COUNT_C], [COUNT_D], [COUNT_E], [COUNT_F], [COUNT_G], [COUNT_H], [COUNT_I])
) upvt
)
SELECT *
FROM D
PIVOT
( SUM(A)
FOR [Type] IN ([Value], [Count])
) pvt;
你也可以在需要通過查詢列名的系統視圖做到這一點動態。
附錄
剛剛意識到這可能是與一個連接而不是UNION和樞軸來實現,我想像的加入,因爲它消除了PIVOT操作將有更好的表現。我仍然建議您同時測試兩者,以查看哪種數據最適合您。
WITH Val AS
( SELECT Category = SUBSTRING(B, 7, LEN(B)), A
FROM @T
UNPIVOT
( A
FOR B IN ([VALUE_A], [VALUE_B], [VALUE_C], [VALUE_D], [VALUE_E], [VALUE_F], [VALUE_G], [VALUE_H], [VALUE_I])
) upvt
), Co AS
( SELECT Category = SUBSTRING(B, 7, LEN(B)), A
FROM @T
UNPIVOT
( A
FOR B IN ([COUNT_A], [COUNT_B], [COUNT_C], [COUNT_D], [COUNT_E], [COUNT_F], [COUNT_G], [COUNT_H], [COUNT_I])
) upvt
)
SELECT val.Category,
[Value] = val.A,
[Count] = co.A
FROM val
INNER JOIN co
ON co.Category = val.Category;
如何計數爲每列或價值的計算? – TechDo
你可以從你的表中發佈一些示例數據嗎?很難說出理想的結果。 – Taryn
@techdo它是另一個保存這些信息的應用程序 –