枢轴查询为每一列返回一行

时间:2019-06-03 20:34:20

标签: c# sql-server tsql

我有一个包含5个主要列的表:STEP_ID,ORDER_NUMBER,STEP_NUMBER,STEP_CODE,FACTOR,我想将STEP_CODEs作为列,然后在相关的STEP_CODE下列出所有ORDER_NUMBERs

我尝试了一些透视查询,但都提出了不想要的值。

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(STEP_CODE)
FROM (SELECT DISTINCT STEP_CODE FROM ORDERS_STEPS) AS STEP_CODE

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT ' + @ColumnName + ' 
    FROM ORDERS_STEPS 
    PIVOT(MAX(ORDER_NUMBER) 
          FOR STEP_CODE IN (' + @ColumnName + ')) AS PVTTable'

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

实际数据如下:

STEP_ID ORDER_NUMBER    STEP_NUMBER STEP_CODE   STEP_FACTOR
-------------------------------------------------------------------
1       10              0           S001            1
2       10              1           S002            1
3       10              2           S003            1
4       20              0           S001            1
5       20              1           S002            1
6       20              2           S003            1

预期结果如下:

S001    S002    S003
--------------------
10      10      10
20      20      20

实际结果如下:

S001    S002    S003
--------------------
10      NULL    NULL
NULL    10      NULL
NULL    NULL    10
20      NULL    NULL
NULL    20      NULL
NULL    NULL    20

1 个答案:

答案 0 :(得分:0)

IF OBJECT_ID('TempDB..##ORDERS_STEPS', 'U') IS NOT NULL DROP TABLE ##ORDERS_STEPS

CREATE TABLE ##ORDERS_STEPS
	(
	STEP_ID INT,
	ORDER_NUMBER INT,
	STEP_NUMBER INT,
	STEP_CODE nVARCHAR(10),
	STEP_FACTOR INT
	)


INSERT INTO ##ORDERS_STEPS
(STEP_ID, ORDER_NUMBER, STEP_NUMBER, STEP_CODE, STEP_FACTOR)
VALUES
(1, 10,0,'S001', 1),
(2, 10,1,'S002', 1),
(3, 10,2,'S003', 1),
(4, 20,0,'S001', 1),
(5, 20,1,'S002', 1),
(6, 20,2,'S003', 1)

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(STEP_CODE)
FROM (SELECT DISTINCT STEP_CODE FROM ##ORDERS_STEPS) AS STEP_CODE

DECLARE @ColumnValue AS NVARCHAR(MAX)
SELECT @ColumnValue= ISNULL(@ColumnValue + ', CASE WHEN ' + QUOTENAME(STEP_CODE) + ' > 0 THEN ORDER_NUMBER END AS ' +  QUOTENAME(STEP_CODE),'CASE WHEN ' +  QUOTENAME(STEP_CODE) + '  > 0 THEN ORDER_NUMBER END AS ' + QUOTENAME(STEP_CODE)) + CHAR(13)
FROM (SELECT DISTINCT STEP_CODE FROM ##ORDERS_STEPS) AS STEP_CODE

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT ' + @ColumnValue + '
    FROM (SELECT STEP_ID, ORDER_NUMBER, STEP_CODE FROM ##ORDERS_STEPS) mq
    PIVOT(COUNT(STEP_ID) 
    FOR STEP_CODE IN (' + @ColumnName + ')) AS pt'

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery