动态透视 SQL 数据 table 与摘要

Dynamically Pivot a SQL data table with summary

我有以下数据 table 是通过读取条形码并相应地包装一些服装的过程生成的,我想要做的是将此 table 转换为此打包过程的摘要。

我的来源table:

我想要达到的结果是这样的:

我试着用下面的代码来做,但结果有问题,它只返回一种尺寸和所有颜色。

IF OBJECT_ID('tempdb..##TBL_TEMP') IS NOT NULL
    DROP TABLE ##TBL_TEMP

-- This parameter will hold the dynamically created SQL script
DECLARE @SQLQuery AS NVARCHAR(MAX)

--This parameter will hold the Pivoted Column values
DECLARE @PivotColumns AS NVARCHAR(MAX)

SELECT @PivotColumns = (SELECT DISTINCT [Size])
FROM [dbo].[Tabel]

--Create the dynamic query with all the values for
--pivot column at runtime
--LIST ALL FILEDS EXCEPT PIVOT COLUMN

SET @SQLQuery =
   N'SELECT [ColorName]' +   @PivotColumns + '
   INTO ##TBL_TEMP
   FROM [dbo].[Tabel]

   PIVOT( MAX([Qty])
      FOR [Size] IN (' + @PivotColumns + ')) AS Q'

--Execute dynamic query
EXEC sp_executesql @SQLQuery

/* VIEW PIVOTED TABLE RESULTS */
Select * from ##TBL_TEMP

你能帮我用C#得到结果吗

我认为您在查询中遗漏了一些细节。在您的数据透视列和动态查询的 Select 语句中尝试这些小的更改。

只需在动态 SQL select 查询中添加 BoxNo 和 StyleCode 并 PIVOT SUM[Qty]

的数据
 SET   @SQLQuery =
 N'SELECT [BoxNo],[StyleCode],[ColorName],' +   @PivotColumns + '
 INTO ##TBL_TEMP
 FROM [dbo].[Tabel]

 PIVOT(SUM([Qty]) 
   FOR [Size] IN (' + @PivotColumns + ')) AS Q'

 --Execute dynamic query
 EXEC sp_executesql @SQLQuery

 --VIEW PIVOTED TABLE RESULTS--
 SELECT * FROM  ##TBL_TEMP

请看我的示例数据截图

现在试试这段代码:

Select BoxNo,StyleCode,ColorName,Size,Qty 
INTO #tbl_1 
FROM [dbo].[1202-904200]

DECLARE   @SQLQuery AS NVARCHAR(MAX)
DECLARE  @PivotColumns AS NVARCHAR(MAX)
SELECT  @PivotColumns= ISNULL(@PivotColumns + ',','') + QUOTENAME([Size]) FROM 
(SELECT DISTINCT [Size] FROM #tbl_1) as Size 

--Create the dynamic query with all the values for pivot column at runtime.
SET @SQLQuery =  N'SELECT [BoxNo],[StyleCode],[ColorName],' + @PivotColumns + '
                 INTO ##TBL_TEMP
                 FROM #tbl_1 -- Replace your source here to #tbl_1
                 PIVOT(SUM([Qty]) 
                 FOR [Size] IN (' + @PivotColumns + ')) AS Q'

--Execute dynamic query
EXEC sp_executesql @SQLQuery

/* VIEW PIVOTED TABLE RESULTS */
SELECT * FROM  ##TBL_TEMP