SQL Server:行到列的互换

时间:2019-02-01 10:11:09

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

我的样本数据

Month Name    MaterialName                                Qty
August        M.Sand(Premium M sand concrete)             0.000
December      M.Sand(Premium M sand Plaster -THRIVENI)    24.950
January       M.Sand(Premium M sand concrete)             527.730
January       20MM                                        68.730
January       M.Sand(Premium M sand Plaster -THRIVENI)    333.040
January       12MM                                        41.480
January       6MM                                         135.000
January       GSB                                         78.300
January       TP SAND BAG                                 55.000
November      M.Sand(Premium M sand concrete)             45.000
October      20MM                                         30.000
September    M.Sand(Premium M sand concrete)              40.000

扩展结果:

Month Name | M.Sand(Premium M sand concrete) | M.Sand(Premium M sand Plaster -THRIVENI) | 20MM      
August     |         0.000           |      0.000               | 0.000
December   |         0.000           |      24.950              | 0.000
January    |         527.730             |      0.000               | 68.730

etc....

请为以上问题提供合适的解决方案。 结果如下图所示:

enter image description here

但是我想要这样的数据:

enter image description here

我的查询:

SELECT DATENAME(MONTH, TripDate) [Month Name],
       MM.MaterialName,
       ISNULL(SUM([NetWeight]), 0) Qty
FROM [TRANS].[tblWeighBridgeEntry] WB
LEFT JOIN MAS.tblMaterialMaster MM ON MM.MaterialID = WB.RefMaterialId
WHERE TripDate IS NOT NULL
  AND TripDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, DATEADD(M, -6, CURRENT_TIMESTAMP)), 0)
GROUP BY DATENAME(MONTH, TripDate),
         RefMaterialId,
         MaterialName

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

np.array(glasses_label)

您只需要获取MaterialName的完全匹配项(在上面的示例中,我尝试复制图片中的内容,但这可能会有一些错误),然后查找,获取,求和。您可以在所有列上执行相同的操作,也可以使用PIVOT进行此操作。

答案 1 :(得分:0)

尝试一下:

SELECT  DATENAME(MONTH,TripDate) [Month Name],MM.MaterialName, ISNULL(SUM([NetWeight]),0) Qty
INTO #DataSource
FROM [TRANS].[tblWeighBridgeEntry] WB
LEFT JOIN MAS.tblMaterialMaster MM ON MM.MaterialID = WB.RefMaterialId
WHERE TripDate IS NOT NULL AND  TripDate  >=  DATEADD(MONTH, DATEDIFF(MONTH, 0, DATEADD(M, -6, CURRENT_TIMESTAMP)), 0) 
GROUP BY DATENAME(MONTH, TripDate),RefMaterialId,MaterialName 


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

SELECT @ColumnNames = STUFF
(
    (
        SELECT DISTINCT ',[' + MaterialName + ']'
        FROM #DataSource
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
   ,1
   ,1
   ,''
);

SET @DynamicTSQLStatement = N'
select ' + @ColumnNames + '
from ##DataSource
PIVOT 
(
    MAX([Qty]) FOR [key] IN (' + @ColumnNames + ')
) PVT
FOR JSON PATH;
';


EXEC sp_executesql @DynamicTSQLStatement;