最後に、いろいろ試した結果、自分のやりたいことができました。ピータームの提案はうまくいきました。共有のために、以下は私が使用する動的ピボットです。
DECLARE @Columns NVARCHAR(MAX)
,@query NVARCHAR(MAX)
SELECT @Columns = STUFF(
(SELECT ', ' +'['+WorkWeek+']' FROM
(SELECT TOP 10 WorkWeek FROM(SELECT TOP 10 WorkWeek , LotTrackingID FROM tblLotTracking ORDER BY LotTrackingID DESC) s Order by s.LotTrackingID) AS T FOR XML PATH('')),1,2,'')
SET @query = N'WITH unpivot_details AS
(
SELECT WorkWeek, Type, Value
FROM
(
SELECT WorkWeek, CometsFT, CometsTR, CSP, MaxCIMFT, MaxCIMTR, MaxCIMWS, STD
FROM tblLotTrackingDetails
) s
UNPIVOT
(
Value FOR Type IN (CometsFT, CometsTR, CSP, MaxCIMFT, MaxCIMTR, MaxCIMWS, STD)
) s
)
SELECT Type RowLabels,
' + @Columns + '
FROM
(
SELECT WorkWeek, Type, Value
FROM unpivot_details
UNION ALL
SELECT WorkWeek, ''Total'', SUM(Value) Value
FROM unpivot_details
GROUP BY WorkWeek
) s
PIVOT
(
SUM(Value) FOR WorkWeek IN(' + @Columns + ')
) p
ORDER BY CASE WHEN Type = ''Total'' THEN 1 ELSE 0 END,
Type';
EXEC sp_executesql @query;