带MAX的SQL数据透视表

时间:2017-10-20 04:48:45

标签: sql pivot max

我坚持这个。我开发了一个SQL脚本来获取这些信息: -

Result

以下是代码: -

SELECT [COST UNIT],[GL ACCOUNT]+ ' ' + [GL], SUM([CLOSING BALANCE]) AS [TOTAL GL CLOSING BALANCE] FROM 
(
    SELECT AB.StartDate AS [DATE], AB.FreeTextField_04 AS [COST UNIT], IT.GLAccountDistribution AS [GL ACCOUNT], GL.Description AS [GL], ST.ItemCode AS [ITEM CODE] , 
    ST.Description AS [DESCRIPTION],
    IT.UserField_03 AS PACKAGING, ST.StockOnHandUOM AS [U/MEA.], IT.CostPriceStandard AS [STD COST PRICE], ST.PhyStkTakeQty AS [STOCK QTY], 
    CAST(ROUND((ST.PhyStkTakeQty * IT.CostPriceStandard ),2) AS DECIMAL(12,2)) AS [CLOSING BALANCE]
    FROM [001].DBO.CS738281StkTake ST INNER JOIN [001].DBO.Absences AB ON ST.ReqID = AB.ID 
    INNER JOIN [200].DBO.Items IT ON ST.ItemCode = IT.ItemCode
    INNER JOIN [200].DBO.GRV_GLAccounts GL ON IT.GLAccountDistribution = GL.GLAccount
    WHERE AB.StartDate = '2017-08-31 0:00:00.000'
    --AND AB.FreeTextField_02 in ( '1CTY','bsp')
    AND IT.GLAccountDistribution IN (12010010,12010020,12010030,12010040,12010041,12010042,12010043,12010050,12010060,12010080,12030010)
    --ORDER BY [GL ACCOUNT],[ITEM CODE]
) tmp
GROUP BY [GL ACCOUNT], [GL], [COST UNIT]
ORDER BY [COST UNIT],[GL ACCOUNT]

我的目标是将数据透视表看起来像这样: - Required Result

我尝试了很多次却无法工作。有人可以帮忙吗?非常感谢你:))

1 个答案:

答案 0 :(得分:0)

PIVOT表格运算符与MAX一起使用,如下所示:

WITH CTE
AS
(
    SELECT [COST UNIT],[GL ACCOUNT]+ ' ' + [GL], SUM([CLOSING BALANCE]) AS [TOTAL GL CLOSING BALANCE] FROM 
    (


         SELECT AB.StartDate AS [DATE], AB.FreeTextField_04 AS [COST UNIT], IT.GLAccountDistribution AS [GL ACCOUNT], GL.Description AS [GL], ST.ItemCode AS [ITEM CODE] , 
            ST.Description AS [DESCRIPTION],
            IT.UserField_03 AS PACKAGING, ST.StockOnHandUOM AS [U/MEA.], IT.CostPriceStandard AS [STD COST PRICE], ST.PhyStkTakeQty AS [STOCK QTY], 
            CAST(ROUND((ST.PhyStkTakeQty * IT.CostPriceStandard ),2) AS DECIMAL(12,2)) AS [CLOSING BALANCE]
            FROM [001].DBO.CS738281StkTake ST INNER JOIN [001].DBO.Absences AB ON ST.ReqID = AB.ID 
            INNER JOIN [200].DBO.Items IT ON ST.ItemCode = IT.ItemCode
            INNER JOIN [200].DBO.GRV_GLAccounts GL ON IT.GLAccountDistribution = GL.GLAccount
            WHERE AB.StartDate = '2017-08-31 0:00:00.000'
            --AND AB.FreeTextField_02 in ( '1CTY','bsp')
            AND IT.GLAccountDistribution IN (12010010,12010020,12010030,12010040,12010041,12010042,12010043,12010050,12010060,12010080,12030010)
            --ORDER BY [GL ACCOUNT],[ITEM CODE]

    ) tmp
    GROUP BY [GL ACCOUNT], [GL], [COST UNIT]
)
SELECT *
FROM
(
    SELECT GL, [COST UNIT], [TOTAL GL CLOSING BALANCE]
    FROM CTE 
) AS t
PIVOT
(
  MAX([TOTAL GL CLOSING BALANCE])
  FOR [COST UNIT] IN([1CTY], [AMCP], [AMPO])
) AS p