将来自SQL Server查询的数据转置为列

时间:2014-04-07 11:29:43

标签: sql sql-server transpose

我有以下查询来从多个表中获取数据

SELECT TOP (100) PERCENT 
   dbo.tblProduct.PK AS PRODUCT_PK, dbo.tblProduct.PRODUCT_NAME, 
   dbo.tblProductSubComponent.SUB_COMPONENT_PK, 
   dbo.tblComponent.COMPONENT_NAME, dbo.tblSubComponent.SUB_COMPONENT_NAME
FROM         
   dbo.tblProductComponent 
RIGHT OUTER JOIN
   dbo.tblComponent 
INNER JOIN
   dbo.tblSubComponent 
INNER JOIN
   dbo.tblComponentSubComponent ON dbo.tblSubComponent.PK = dbo.tblComponentSubComponent.SUB_COMPONENT_PK 
       ON dbo.tblComponent.PK = dbo.tblComponentSubComponent.COMPONENT_PK 
       ON dbo.tblProductComponent.COMPONENT_PK = dbo.tblComponent.PK 
LEFT OUTER JOIN
   dbo.tblProductSubComponent ON dbo.tblSubComponent.PK = dbo.tblProductSubComponent.SUB_COMPONENT_PK 
FULL OUTER JOIN
   dbo.tblProduct ON dbo.tblProductSubComponent.PRODUCT_PK = dbo.tblProduct.PK AND dbo.tblProductComponent.PRODUCT_PK = dbo.tblProduct.PK
ORDER BY 
    PRODUCT_PK

结果是

The result

现在我想在gridview中显示这样的数据

Desired result

1 个答案:

答案 0 :(得分:0)

没关系..我自己解决了。创建了一个存储过程来获取数据并将其存储在表变量中,然后使用alter column query将我的行添加为临时表的列。 在创建临时表之后,我循环遍历每个组件并为每个组件和子组件插入记录。