PIVOT查询中的总计列将忽略具有NULL值的记录

时间:2019-04-17 20:56:51

标签: sql sum isnull

此交叉表查询中的总计列将其左侧的十二个M1,M2 .... M12列求和。问题是Total列对于所有记录返回0值,其中M列中至少有一个为零。我在需要的任何地方都添加了非空条件,但仍然不起作用。

    SELECT 
         [Prop] as 'Company'
        ,[Category_EXCO] as 'Account Category'
        ,[CenterNum] as 'CenterNumber'
        ,[AccountNum] as 'Account'
        ,[Account_Description] as 'Description'
        ,case when [Is_Revenue] = 1 then 'TRUE' else 'FALSE' end as 'RevorExp'
        , case when [Is_Above_EBITDA] = 1 then 'TRUE' else 'FALSE' end as 'EBITDA'
        ,format(isnull(M1,0),'#,#0.00') as M1
        ,format(isnull(M2,0),'#,#0.00') as M2
        ,format(isnull(M3,0),'#,#0.00') as M3
        ,format(isnull(M4,0),'#,#0.00') as M4
        ,format(isnull(M5,0),'#,#0.00') as M5
        ,format(isnull(M6,0),'#,#0.00') as M6
        ,format(isnull(M7,0),'#,#0.00') as M7
        ,format(isnull(M8,0),'#,#0.00') as M8
        ,format(isnull(M9,0),'#,#0.00') as M9
        ,format(isnull(M10,0),'#,#0.00') as M10
        ,format(isnull(M11,0),'#,#0.00') as M11
        ,format(isnull(M12,0),'#,#0.00') as M12 
        ,format(isnull(M1+M2+M3+M4+M5+M6+M7+M8+M9+M10+M11+M12,0),'#,#0.00') as TOTAL
        ,[Division_Description] as Division
        ,case when [Is_F&B1] = 1 then 'F&B Consolidated' else 'Non-F&B' end as Division_1
        ,[Group_Description] as 'Group'
        ,case when [Group_Description] = 'RWNY Operations' THEN 'NEW YORK' ELSE 'FLORIDA' END as 'Region'
        ,CONCAT ([AccountNum],'_',[CenterNum]) as 'Acct+Center'

--The code generates a flat table to be used to fill the columns in the crosstab query
    FROM 
        (
        SELECT 
         tblCenters.prop
        ,tblAccounts.Category_EXCO
        ,tblCenters.CenterNum
        ,tblAccounts.AccountNum
        ,tblAccounts.Account_Description
        ,tblAccounts.Is_Revenue
        ,tblAccounts.Is_Above_EBITDA
        ,tblCenters.Division_Description
        ,tblCenters.[Is_F&B1]
        ,tblCenters.Group_Description
        ,isnull(tblsap.Entry,0) Entry
        ,MX
            FROM GA_Financial.dbo.tblSAP 

            left join DateTable on tblSAP.MDY = DateTable.MDY
            left join tblAccounts on tblSAP.AccountNum = tblAccounts.AccountNum
            left join tblCenters on tblSAP.CenterNum = tblCenters.CenterNum and tblSAP.Prop_SAP = tblCenters.PROP_SAP

            WHERE tblAccounts.Is_Above_EBITDA = 1
            AND tblSAP.BudAct = 'A'

        ) 

    AS Tab1
--The code below breaks down column "Entry" into twelve individual monthly columns and fills columns M1 through M12
    PIVOT
        (

        SUM(entry) for MX in (M1,M2,M3,M4,M5,M6,M7,M8,M9,M10,M11,M12)
        ) as TAb2

        where Prop = 'RWNY'

0 个答案:

没有答案