Pivot values on column based on grouped columns in SQL(基于 SQL 中的分组列在列上透视值)
                            本文介绍了基于 SQL 中的分组列在列上透视值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
                        
                        问题描述
我想根据组将值转置到列.但是,我事先并不知道这些值.
I want to pivot values to columns based on a group. However, I do not know the values beforehand.
一个查询给了我这个结果.
A query gives me this result.
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
推荐答案
如果你现在知道结果中有多少列,你需要使用动态 T-SQL 语句来构建 PIVOT代码>.例如:
If you do now know how many column you are going to have in the result, you need to use dynamic T-SQL statement to build the PIVOT. For example:
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;
                        这篇关于基于 SQL 中的分组列在列上透视值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:基于 SQL 中的分组列在列上透视值
				
        
 
            
        
             猜你喜欢
        
	     - 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
 - 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
 - 更改自动增量起始编号? 2021-01-01
 - 导入具有可变标题的 Excel 文件 2021-01-01
 - 在SQL中,如何为每个组选择前2行 2021-01-01
 - 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
 - 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
 - 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
 - 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
 - SQL 临时表问题 2022-01-01
 
						
						
						
						
						
				
				
				
				