我们如何将列更改为sql中的行

时间:2016-09-26 07:27:51

标签: sql-server sql-server-2008 sql-server-2012

如何从以下查询中使列SubInventory在SQL Server中排?这里的产品是第一列,然后是行中的子库存,带有产品详细信息。

在这张照片中你可以看到子库存,因为我在行中需要它

SELECT 
    BRCH.BranchName [BranchName],
    ASI.SubInventoryName [SubInventory],
    APRO.ProductName [Product],
    ASICT.TransactDateTime [DateTime],
    ASICT.ProductStock [Stock],
    ASICT.ProductStockInLocalCrrncy [Local Stock]
FROM 
    ALX_SubInventoryCashTransfers ASICT
INNER JOIN 
    ALX_Branches BRCH ON BRCH.BranchID = ASICT.BranchID
INNER JOIN 
    ALX_SubInventories ASI ON ASI.SubInventoryID = ASICT.SubInventoryID
INNER JOIN 
    ALX_Products APRO ON APRO.ProductID = ASICT.ProductID
INNER JOIN 
    (SELECT
         BranchID, SubInventoryID, ProductID,
         MAX(TransactDateTime) AS MaxDate
     FROM 
         ALX_SubInventoryCashTransfers                            
     GROUP BY 
         BranchID, SubInventoryID, ProductID) SubASICT ON ASICT.BranchID = SubASICT.BranchID
                                                       AND ASICT.SubInventoryID = SubASICT.SubInventoryID
                                                       AND ASICT.ProductID = SubASICT.ProductID
                                                       AND ASICT.TransactDateTime = SubASICT.MaxDate

目前的结果是

enter image description here

在这张照片中,您可以看到列中的子库存,它不是计数或平均值或总和,它是一个名称

我需要结果看起来像这样

Reult I need

1 个答案:

答案 0 :(得分:2)

将所有查询结果放入#temp表,然后执行动态数据透视:

DECLARE @sql nvarchar(max),
        @columns nvarchar(max)

SELECT @columns = (
    SELECT DISTINCT ','+QUOTENAME([SubInventory])
    FROM #temp
    FOR XML PATH('')
)

SELECT @sql = N'
SELECT *
FROM (
    SELECT  [SubInventory],
            [Product],
            [Stock]
    FROM #temp
) as t
PIVOT (
    MAX([Stock]) FOR [SubInventory] IN ('+STUFF(@columns,1,1,'')+')
) as pvt'

EXEC sp_executesql @sql