使用动态SQL和pivot命令生成列号

时间:2014-07-01 19:52:35

标签: sql sql-server excel-vba dynamic pivot

我有以下SQL,我想将其转换为具有动态SQL的存储过程,以生成Sale_Week的列号(1到52)。此外,我想使用VBA从Excel调用此存储过程,将2个参数传递给SQL Server中的存储过程 e.g,

DECLARE @KPI nvarchar(MAX)='创新的销售价值' DECLARE @Country nvarchar(MAX)='UK'

我想将生成的旋转表重新抓取到excel中。怎么做?

USE [Database_ABC]
GO

DECLARE @KPI nvarchar(MAX) = 'Sales Value with Innovation'
DECLARE @Country nvarchar(MAX) = 'UK'

SELECT [sCHAR],[sCOUNTRY],[Category],[Manufacturer],[Brand],[Description],[1],[2],
[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],
[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31],[32],[33],[34],[35],[36],
[37],[38],[39],[40],[41],[42],[43],[44],[45],[46],[47],[48],[49],[50],[51],[52]
FROM 
(
SELECT [sCHAR]
,[sCOUNTRY]
,[Category]
,[Manufacturer]
,[Brand]
,[Description]
,[Sales Value with Innovation]
,[Sale_Week]
FROM [dbo].[ItemTable]
WHERE sCOUNTRY='UK' 
) AS T 
PIVOT
(
SUM([Sales Value with Innovation])
for Sale_Week IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],
[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],
[31],[32],[33],[34],[35],[36],[37],[38],[39],[40],[41],[42],[43],[44],[45],[46],
[47],[48],[49],[50],[51],[52])
) AS PT
ORDER BY PT.SCHAR, PT.sCOUNTRY, PT.Category,PT.Manufacturer, PT.Brand, PT.Description
GO

非常感谢任何帮助。

0 个答案:

没有答案