根据SQL中的分组列在列上透视值

时间:2017-05-19 05:36:40

标签: sql sql-server tsql pivot

我想根据组将值转换为列。但是,我事先并不知道这些值。

查询给了我这个结果。

Id          Code         EntityId
----------- ------------ -------------
3           22209776     1
4           143687971    3
4           143687971    4
4           143687971    5
4           143687971    15
5           143658155    7
5           143658155    8

我想输出这个

Id          Code         EntityId1     EntityId2     EntityId3     EntityId4
----------- ------------ ------------- ------------- ------------- -------------
3           22209776     1             NULL          NULL          NULL
4           143687971    3             4             5             15
5           143658155    7             8             NULL          NULL

2 个答案:

答案 0 :(得分:1)

如果您现在知道结果中将包含多少列,则需要使用动态T-SQL语句来构建PIVOT。例如:

IF OBJECT_ID('tempdb..#DataSource') IS NOT NULL
BEGIN;
    DROP TABLE #DataSource;
END;

CREATE TABLE #DataSource
(
    [id] INT
   ,[Code] INT
   ,[EntityId] INT
);

DECLARE @DynamicTSQLStatement NVARCHAR(MAX)
       ,@Columns NVARCHAR(MAX);

DECLARE @MaxColumns INT;

INSERT INTO #DataSource ([id], [Code], [EntityId])
VALUES (3, 22209776 , 1)
      ,(4, 143687971, 3)
      ,(4, 143687971, 4)
      ,(4, 143687971, 5)
      ,(4, 143687971, 15)
      ,(5, 143658155, 7)
      ,(5, 143658155, 8)
      ,(4, 143687971, 25)
      ,(4, 143687971, 26);

-- we need to know how many columns are going to be shown
SELECT TOP 1 @MaxColumns = COUNT(*)
FROM #DataSource
GROUP BY [Code]
ORDER BY COUNT(*) DESC;

-- we are building here the following string '[1],[2],[3],[4],[5],[6]'; 
-- this will change depending the input data
WITH gen AS 
(
    SELECT 1 AS num
    UNION ALL
    SELECT num+1 
    FROM gen 
    WHERE num+1<=@MaxColumns
)
SELECT @Columns = STUFF
(
    (
        SELECT ',[EntityId' + CAST([num] AS VARCHAR(12)) + ']'
        FROM gen
        FOR XML PATH(''), TYPE

    ).value('.', 'VARCHAR(MAX)')
    ,1
    ,1
    ,''
)
OPTION (maxrecursion 10000);

SET @DynamicTSQLStatement = N'
SELECT *
FROM 
( 
    SELECT [id]
          ,[Code]
          ,[EntityId]
          ,''EntityId'' + CAST(ROW_NUMBER() OVER(PARTITION BY [Code] ORDER BY [EntityId]) AS VARCHAR(12))
    FROM #DataSource
) DS ([id], [Code], [EntityId], [RowID])
PIVOT 
(
    MAX([EntityId]) for [RowID] in (' + @Columns +')
) PVT;';

EXEC sp_executesql @DynamicTSQLStatement;

enter image description here

答案 1 :(得分:0)

您可以尝试使用pivot功能:

-fx-pref-height