Sql 使用透视表将重复的行值转换为列

Sql 使用透视表将重复的行值转换为列,sql,stored-procedures,pivot-table,sql-server-2014,Sql,Stored Procedures,Pivot Table,Sql Server 2014,这是我的存储过程查询,用于获取第一个表中的数据 SELECT [Item] = t3.Item, [Name] = t2.Name, [Value] = t1.value INTO #Result FROM table1 t1 INNER JOIN table2 t2 ON t2.IsDeleted = 0 INNER JOIN table3 t3 ON t3.IsDeleted = 0 AND t3.Item_ID = @Id WHERE t1.Item_ID = @Id GROUP

这是我的存储过程查询,用于获取第一个表中的数据

SELECT [Item] = t3.Item,
[Name] = t2.Name,
[Value] = t1.value

INTO #Result

FROM table1 t1
INNER JOIN table2 t2 ON t2.IsDeleted = 0
INNER JOIN table3 t3 ON t3.IsDeleted = 0 AND t3.Item_ID = @Id
WHERE t1.Item_ID = @Id 

GROUP BY 
t1.value,
t2.Name,
t3.Item
我在临时表中有以下数据

|  Item |  Name  | Value |
--------------------------
| item1 | Name 1 |   2   |
| item2 | Name 1 |   4   |
| item3 | Name 1 |   5   |
| item1 | Name 2 |   6   |
| item2 | Name 2 |   3   |
| item3 | Name 2 |   1   |
| item1 | Name 3 |   7   |
| item2 | Name 3 |   4   |
| item3 | Name 3 |   2   |
我希望将名称1、名称2、名称3作为列,并将它们的
对应于相应的项。表中的数据是动态的。可以有任意数量的
和任意数量的
名称
。对于每个
名称
项目
而言,它们都是一个可以是一位数字的值<代码>项目对于每个
名称都是相同的
谢谢

我需要下面这样的东西

|  Item | Name 1 | Name 2 | Name 3|
------------------------------------
| item1 |    2   |    6   |   7   |
| item2 |    4   |    3   |   4   |
| item3 |    5   |    1   |   2   |
使用

如果您的名称不是常量,并且可能不同,则应该创建动态sql查询(您可以找到动态查询的示例)。

这对我来说很有效。:)


为什么可以使用存储过程标记?GROUP BY。将用于所有dbms产品。因为我需要在存储过程中使用它。如果需要,我可以发布我的存储过程。请添加您的存储过程标记您正在使用的dbms。大多数产品都有自己的非ANSI SQL存储过程版本。
declare @T table
(
    item varchar(5),
    name varchar(6),
    value smallint
)

insert into @T
select 'item1' , 'Name 1' , 2 union
select 'item2' , 'Name 1' , 4 union
select 'item3' , 'Name 1' , 5 union
select 'item1' , 'Name 2' , 6 union
select 'item2' , 'Name 2' , 3 union
select 'item3' , 'Name 2' , 1 union
select 'item1' , 'Name 3' , 7 union
select 'item2' , 'Name 3' , 4 union
select 'item3' , 'Name 3' , 2 

select * 
from
(
    select * from @T
) p
pivot
(
    sum(value) for name in ([Name 1], [Name 2], [Name 3])
) pvt
IF OBJECT_ID('TEMPDB.dbo.##FinalResult ') IS NOT NULL DROP TABLE ##FinalResult 

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

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME([Name])     
FROM (SELECT DISTINCT [Name] FROM #Result) AS ##FinalResult 

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT [Item], ' + @ColumnName + '
    INTO ##FinalResult 
    FROM #Result 
    PIVOT(MAX([Value])
    FOR [Name] IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

SELECT * FROM ##FinalResult