Can't get union to work - sql

I have a rather long query, and I got it to work, kind of. I can;t get the two unions to work since both have different FROM clauses (I THINK)
I think it would be best to post most of it because it is very convoluted. sorry if it takes up so much space.
SELECT
ISNULL(#tempBacklog.Division, #tempCompleteNotInvoiced.Division) AS 'Division',
'NONE' as 'Division ID',
'NONE' as 'NAME',
'NONE' AS 'Sales Engineer',
0.00 As 'Current MTD SALES',
0.00 As 'Last Year MTD SALES',
0.00 as 'Projected MTD Sales',
ISNULL(Backlog, 0) AS 'Backlog',
ISNULL([Complete Not Invoiced], 0) AS 'Completed Not Invoiced',
ISNULL(#tempBacklog.CUSTACCOUNT, #tempCompleteNotInvoiced.CUSTACCOUNT) AS 'accountnum'
FROM
--#tempSales FULL OUTER JOIN
#tempBacklog FULL OUTER JOIN
#tempCompleteNotInvoiced ON #tempBacklog.ITEMGROUPID = #tempCompleteNotInvoiced.ITEMGROUPID
AND #tempBacklog.Division = #tempCompleteNotInvoiced.Division
AND #tempBacklog.[Ledger Account] = #tempCompleteNotInvoiced.[Ledger Account]
AND #tempBacklog.CUSTACCOUNT = #tempCompleteNotInvoiced.CUSTACCOUNT
union all
--Temp table for JE voucher entries , because of dupilacte entries in Custinvoice and CustInoviceJour table
select Division,
[Division ID],
[NAME],
CASE WHEN IsNull([Sales Engineer],'')='' Then Division+'-UnKnown' ELSE [Sales Engineer] END AS 'Sales Engineer',
(case WHEN MONTH(GETDATE()) = 1 then SUM([1])
WHEN MONTH(GETDATE()) = 2 then SUM([2])
WHEN MONTH(GETDATE()) = 3 THEN SUM([3])
WHEN MONTH(GETDATE()) = 4 THEN SUM([4])
WHEN MONTH(GETDATE()) = 5 THEN SUM([5])
WHEN MONTH(GETDATE()) = 6 THEN SUM([6])
WHEN MONTH(GETDATE()) = 7 THEN SUM([7])
WHEN MONTH(GETDATE()) = 8 THEN SUM([8])
WHEN MONTH(GETDATE()) = 9 THEN SUM([9])
WHEN MONTH(GETDATE()) = 10 THEN SUM([10])
WHEN MONTH(GETDATE()) = 11 THEN SUM([11])
WHEN MONTH(GETDATE()) = 12 THEN SUM([12])
END) As 'Current MTD SALES',
(case WHEN MONTH(GETDATE()) = 1 then SUM([L1])
WHEN MONTH(GETDATE()) = 2 then SUM([L2])
WHEN MONTH(GETDATE()) = 3 THEN SUM([L3])
WHEN MONTH(GETDATE()) = 4 THEN SUM([L4])
WHEN MONTH(GETDATE()) = 5 THEN SUM([L5])
WHEN MONTH(GETDATE()) = 6 THEN SUM([L6])
WHEN MONTH(GETDATE()) = 7 THEN SUM([L7])
WHEN MONTH(GETDATE()) = 8 THEN SUM([L8])
WHEN MONTH(GETDATE()) = 9 THEN SUM([L9])
WHEN MONTH(GETDATE()) = 10 THEN SUM([L10])
WHEN MONTH(GETDATE()) = 11 THEN SUM([L11])
WHEN MONTH(GETDATE()) = 12 THEN SUM([L12])
END) As 'Last Year MTD SALES',
(case WHEN MONTH(GETDATE()) = 1 then SUM([YTD1])
WHEN MONTH(GETDATE()) = 2 then SUM([YTD2])
WHEN MONTH(GETDATE()) = 3 THEN SUM([YTD3])
WHEN MONTH(GETDATE()) = 4 THEN SUM([YTD4])
WHEN MONTH(GETDATE()) = 5 THEN SUM([YTD5])
WHEN MONTH(GETDATE()) = 6 THEN SUM([YTD6])
WHEN MONTH(GETDATE()) = 7 THEN SUM([YTD7])
WHEN MONTH(GETDATE()) = 8 THEN SUM([YTD8])
WHEN MONTH(GETDATE()) = 9 THEN SUM([YTD9])
WHEN MONTH(GETDATE()) = 10 THEN SUM([YTD10])
WHEN MONTH(GETDATE()) = 11 THEN SUM([YTD11])
WHEN MONTH(GETDATE()) = 12 THEN SUM([YTD12])
END) as 'Projected MTD Sales',
SUM(Backlog) AS 'Backlog',
SUM([Completed Not Invoiced]) AS 'Completed Not Invoiced'
,accountnum
from
(
select
IsNULL([DESCRIPTION],'None') as Division,
LT.[DIMENSION2_] AS 'Division ID',
'NONE' as 'NAME',
'NONE' as 'ACCOUNTNUM',
'NONE' AS 'Industry',
'NONE' as 'Street',
'NONE' as 'City',
'NONE' as 'State',
'NONE' as 'ZipCode',
'' as 'Sales Engineer',--IsNULL([DESCRIPTION],'None')+'-UnKnown' AS 'Sales Engineer',
'NONE' as 'SalesGroup',
'' as 'SALESMANID',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #1Start AND #YTD THEN LT.[AMOUNTMST] ELSE 0 END) AS 'YTD Sales',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #1Start AND #1End THEN LT.[AMOUNTMST] ELSE 0 END) AS '1',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #2Start AND #2End THEN LT.[AMOUNTMST] ELSE 0 END) AS '2',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #3Start AND #3End THEN LT.[AMOUNTMST] ELSE 0 END) AS '3',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #4Start AND #4End THEN LT.[AMOUNTMST] ELSE 0 END) AS '4',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #5Start AND #5End THEN LT.[AMOUNTMST] ELSE 0 END) AS '5',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #6Start AND #6End THEN LT.[AMOUNTMST] ELSE 0 END) AS '6',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #7Start AND #7End THEN LT.[AMOUNTMST] ELSE 0 END) AS '7',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #8Start AND #8End THEN LT.[AMOUNTMST] ELSE 0 END) AS '8',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #9Start AND #9End THEN LT.[AMOUNTMST] ELSE 0 END) AS '9',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #10Start AND #10End THEN LT.[AMOUNTMST] ELSE 0 END) AS '10',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #11Start AND #11End THEN LT.[AMOUNTMST] ELSE 0 END) AS '11',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #12Start AND #12End THEN LT.[AMOUNTMST] ELSE 0 END) AS '12',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #LYTD_Start AND #LYTD_End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'Last YTD Sales',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #LYS_Start AND #LYS_End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'Last Year Sales',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L1Start AND #L1End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L1',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L2Start AND #L2End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L2',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L3Start AND #L3End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L3',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L4Start AND #L4End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L4',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L5Start AND #L5End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L5',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L6Start AND #L6End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L6',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L7Start AND #L7End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L7',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L8Start AND #L8End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L8',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L9Start AND #L9End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L9',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L10Start AND #L10End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L10',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L11Start AND #L11End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L11',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L12Start AND #L12End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L12',
0.00 as 'Projection',
0.00 AS 'YTD Projection',
0.00 AS 'YTD1',
0.00 AS 'YTD2',
0.00 AS 'YTD3',
0.00 AS 'YTD4',
0.00 AS 'YTD5',
0.00 AS 'YTD6',
0.00 AS 'YTD7',
0.00 AS 'YTD8',
0.00 AS 'YTD9',
0.00 AS 'YTD10',
0.00 AS 'YTD11',
0.00 AS 'YTD12',
0.00 as 'Year Goal',
'' as 'PROJECTION COMMENT'
,0.00 AS 'Backlog',
0.00 AS 'Completed Not Invoiced'
from dbo.[LedgerTrans] LT
inner Join dbo.[LedgerJournalTrans] LJ on LT.Voucher = LJ.Voucher and LT.TransDate = LJ.TransDate and AccountType = '0'
and LJ.ACCOUNTNUM = LT.ACCOUNTNUM and LT.DIMENSION2_=LJ.DIMENSION2_
and LT.AMOUNTMST = (CASE WHEN AMOUNTCURDEBIT != 0 then AMOUNTCURDEBIT else -1*AMOUNTCURCREDIT END)
Inner JOIN dbo.DIMENSIONS ON NUM = LT.DIMENSION2_
Inner Join dbo.LedgerTable LD on LD.ACCOUNTNUM = LJ.ACCOUNTNUM and LD.ACCOUNTNUM = LT.ACCOUNTNUM
--inner join #tempTotals on LJ.accountnum = #temptotals.[Ledger Account]
where (#reportType = 'Forecasting' and LJ.ACCOUNTNUM between '400100' and '409400' and LT.ACCOUNTNUM between '400100' and '409400' and LJ.DocumentNum = ''
and LT.[DIMENSION2_] != '10' and LD.KTI_OASALESCOMM = 0
AND LT.[DIMENSION2_] in (#dimension))
or
(#reportType = 'Financial' and LJ.DocumentNum = ''
and LT.[DIMENSION2_] != '10'
and LJ.ACCOUNTNUM between '400100' and '409400'
and LT.ACCOUNTNUM between '400100' and '409400'
AND LT.[DIMENSION2_] in (#dimension))
group by
[DESCRIPTION],LT.[DIMENSION2_]
UNION ALL
select
IsNULL(ISNULL(NULLIF(d2.[DESCRIPTION], ''), d1.[DESCRIPTION]),'None') as Division,
IsNULL(ISNULL(NULLIF(d2.NUM, ''), d1.NUM),'None') as 'Division ID',
cu.[NAME] as 'NAME',
cu.[ACCOUNTNUM] as 'ACCOUNTNUM',
BUSINESSSECTORID AS 'Industry',
cu.[STREET] as 'Street',
cu.[CITY] as 'City',
cu.[STATE] as 'State',
cu.[ZIPCODE] as 'ZipCode',
[Sales Engineer] as 'Sales Engineer',--IsNULL([DESCRIPTION],'None')+'-UnKnown' AS 'Sales Engineer',
cu.[SalesGroup] as 'SalesGroup',
IsNull(tes.SALESMANID,'') as 'SALESMANID',
SUM([YTD Sales]) as 'YTD Sales',SUM([1]) as '1',SUM([2]) as '2',SUM([3]) as '3',SUM([4]) as '4',SUM([5]) as '5'
,SUM([6]) as '6',SUM([7]) as '7',SUM([8]) as '8',SUM([9]) as '9',SUM([10]) as '10',SUM([11]) as '11',SUM([12]) as '12',
SUM([Last YTD Sales]) as 'Last YTD Sales',SUM([Last Year Sales]) as 'Last Year Sales',
SUM([L1]) as 'L1',SUM([L2]) as 'L2',SUM([L3]) as 'L3',SUM([L4]) as 'L4',SUM([L5]) as 'L5'
,SUM([L6]) as 'L6',SUM([L7]) as 'L7',SUM([L8]) as 'L8',SUM([L9]) as 'L9',SUM([L10]) as 'L10',
SUM([L11]) as 'L11',SUM([L12]) as 'L12',
IsNULL(Projection,0.00) as 'Projection',
[YTD Projection] as 'YTD Projection',
ISNULL((Select Top(1) [YTD Projection] from #tempSalesTargetMW where STARTDATE>=#1YTDStart and ENDDATE<=#1YTDEnd and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null) and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD1',
ISNULL((Select Top(1) [YTD Projection] from #tempSalesTargetMW where STARTDATE>=#2YTDStart and ENDDATE<=#2YTDEnd and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null) and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD2',
ISNULL((Select Top(1) [YTD Projection] from #tempSalesTargetMW where STARTDATE>=#3YTDStart and ENDDATE<=#3YTDEnd and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null) and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD3',
ISNULL((Select Top(1) [YTD Projection] from #tempSalesTargetMW where STARTDATE>=#4YTDStart and ENDDATE<=#4YTDEnd and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null) and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD4',
ISNULL((Select Top(1) [YTD Projection] from #tempSalesTargetMW where STARTDATE>=#5YTDStart and ENDDATE<=#5YTDEnd and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null) and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD5',
ISNULL((Select Top(1) [YTD Projection] from #tempSalesTargetMW where STARTDATE>=#6YTDStart and ENDDATE<=#6YTDEnd and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null) and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD6',
ISNULL((Select Top(1) [YTD Projection] from #tempSalesTargetMW where STARTDATE>=#7YTDStart and ENDDATE<=#7YTDEnd and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null) and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD7',
ISNULL((Select Top(1)[YTD Projection] from #tempSalesTargetMW where STARTDATE>=#8YTDStart and ENDDATE<=#8YTDEnd and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null) and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD8',
ISNULL((Select Top(1) [YTD Projection] from #tempSalesTargetMW where STARTDATE>=#9YTDStart and ENDDATE<=#9YTDEnd and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null) and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD9',
ISNULL((Select Top(1) [YTD Projection] from #tempSalesTargetMW where STARTDATE>=#10YTDStart and ENDDATE<=#10YTDEnd and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null) and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD10',
ISNULL((Select Top(1) [YTD Projection] from #tempSalesTargetMW where STARTDATE>=#11YTDStart and ENDDATE<=#11YTDEnd and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null) and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD11',
ISNULL((Select Top(1) [YTD Projection] from #tempSalesTargetMW where STARTDATE>=#12YTDStart and ENDDATE<=#12YTDEnd and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null) and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD12',
[Year Goal] as 'Year Goal',[PROJECTION COMMENT],
0.00 AS 'Backlog',
0.00 AS 'Completed Not Invoiced'
from [CUSTTABLE] cu
Left JOIN
(
select
LT.[DIMENSION2_] AS 'Division ID',
LJ.ACCOUNTNUM as 'ACCOUNTNUM',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #1Start AND #YTD THEN LT.[AMOUNTMST] ELSE 0 END) AS 'YTD Sales',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #1Start AND #1End THEN LT.[AMOUNTMST] ELSE 0 END) AS '1',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #2Start AND #2End THEN LT.[AMOUNTMST] ELSE 0 END) AS '2',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #3Start AND #3End THEN LT.[AMOUNTMST] ELSE 0 END) AS '3',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #4Start AND #4End THEN LT.[AMOUNTMST] ELSE 0 END) AS '4',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #5Start AND #5End THEN LT.[AMOUNTMST] ELSE 0 END) AS '5',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #6Start AND #6End THEN LT.[AMOUNTMST] ELSE 0 END) AS '6',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #7Start AND #7End THEN LT.[AMOUNTMST] ELSE 0 END) AS '7',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #8Start AND #8End THEN LT.[AMOUNTMST] ELSE 0 END) AS '8',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #9Start AND #9End THEN LT.[AMOUNTMST] ELSE 0 END) AS '9',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #10Start AND #10End THEN LT.[AMOUNTMST] ELSE 0 END) AS '10',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #11Start AND #11End THEN LT.[AMOUNTMST] ELSE 0 END) AS '11',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #12Start AND #12End THEN LT.[AMOUNTMST] ELSE 0 END) AS '12',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #LYTD_Start AND #LYTD_End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'Last YTD Sales',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #LYS_Start AND #LYS_End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'Last Year Sales',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L1Start AND #L1End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L1',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L2Start AND #L2End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L2',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L3Start AND #L3End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L3',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L4Start AND #L4End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L4',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L5Start AND #L5End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L5',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L6Start AND #L6End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L6',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L7Start AND #L7End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L7',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L8Start AND #L8End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L8',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L9Start AND #L9End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L9',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L10Start AND #L10End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L10',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L11Start AND #L11End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L11',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L12Start AND #L12End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L12',
LT.[TRANSDATE]
,0.00 AS 'Backlog',
0.00 AS 'Completed Not Invoiced'
from
dbo.[LedgerTrans] LT
inner JOIN dbo.[LedgerJournalTrans] LJ on LT.Voucher = LJ.Voucher and LT.TransDate = LJ.TransDate and AccountType in ('1')
Inner Join dbo.LedgerTable LD on LD.ACCOUNTNUM = LT.ACCOUNTNUM
where
(LT.ACCOUNTNUM between '400100' and '409400')
AND LT.[TRANSDATE] BETWEEN #LYS_Start AND #12End and LT.[DIMENSION2_] = '10' and LT.Voucher Not Like 'JE%'
and LD.KTI_OASALESCOMM = 0 AND LT.[DIMENSION2_] in (#dimension) and #reportType='Forecasting'
or
(LT.[TRANSDATE] BETWEEN #LYS_Start AND #12End and LT.[DIMENSION2_] = '10' and LT.Voucher Not Like 'JE%'
AND LT.ACCOUNTNUM between '400100' and '409400'
AND LT.[DIMENSION2_] in (#dimension) and #reportType='Financial')
group by LJ.ACCOUNTNUM,LT.[DIMENSION2_],LT.[TRANSDATE]
union all
select
LT.[DIMENSION2_] AS 'Division ID',
LJ.ACCOUNTNUM as 'ACCOUNTNUM',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #1Start AND #YTD THEN LT.[AMOUNTMST] ELSE 0 END) AS 'YTD Sales',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #1Start AND #1End THEN LT.[AMOUNTMST] ELSE 0 END) AS '1',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #2Start AND #2End THEN LT.[AMOUNTMST] ELSE 0 END) AS '2',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #3Start AND #3End THEN LT.[AMOUNTMST] ELSE 0 END) AS '3',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #4Start AND #4End THEN LT.[AMOUNTMST] ELSE 0 END) AS '4',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #5Start AND #5End THEN LT.[AMOUNTMST] ELSE 0 END) AS '5',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #6Start AND #6End THEN LT.[AMOUNTMST] ELSE 0 END) AS '6',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #7Start AND #7End THEN LT.[AMOUNTMST] ELSE 0 END) AS '7',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #8Start AND #8End THEN LT.[AMOUNTMST] ELSE 0 END) AS '8',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #9Start AND #9End THEN LT.[AMOUNTMST] ELSE 0 END) AS '9',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #10Start AND #10End THEN LT.[AMOUNTMST] ELSE 0 END) AS '10',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #11Start AND #11End THEN LT.[AMOUNTMST] ELSE 0 END) AS '11',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #12Start AND #12End THEN LT.[AMOUNTMST] ELSE 0 END) AS '12',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #LYTD_Start AND #LYTD_End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'Last YTD Sales',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #LYS_Start AND #LYS_End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'Last Year Sales',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L1Start AND #L1End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L1',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L2Start AND #L2End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L2',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L3Start AND #L3End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L3',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L4Start AND #L4End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L4',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L5Start AND #L5End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L5',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L6Start AND #L6End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L6',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L7Start AND #L7End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L7',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L8Start AND #L8End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L8',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L9Start AND #L9End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L9',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L10Start AND #L10End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L10',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L11Start AND #L11End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L11',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L12Start AND #L12End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L12',
LT.[TRANSDATE]
,0.00 AS 'Backlog',
0.00 AS 'Completed Not Invoiced'
from
dbo.[LedgerTrans] LT
inner JOIN dbo.[LedgerJournalTrans] LJ on LT.Voucher = LJ.Voucher and LT.TransDate = LJ.TransDate and AccountType in ('1')
Inner Join dbo.LedgerTable LD on LD.ACCOUNTNUM = LT.ACCOUNTNUM
where
(LT.ACCOUNTNUM between '400100' and '409400')
AND LT.[TRANSDATE] BETWEEN #LYS_Start AND #12End and LT.[DIMENSION2_] != '10' and LD.KTI_OASALESCOMM = 0 and #reportType = 'Forecasting'
AND LT.[DIMENSION2_] in (#dimension)
or
(LT.[TRANSDATE] BETWEEN #LYS_Start AND #12End and LT.[DIMENSION2_] != '10' and #reportType = 'Financial'
AND LT.ACCOUNTNUM between '400100' and '409400'
AND LT.[DIMENSION2_] in (#dimension))
group by LJ.ACCOUNTNUM,LT.[DIMENSION2_],LT.[TRANSDATE]
) as Cus on (cu.ACCOUNTNUM = Cus.ACCOUNTNUM)
Inner JOIN dbo.DIMENSIONS d1 ON NUM = cu.[dimension2_]
LEFT OUTER JOIN dbo.DIMENSIONS d2 ON d2.NUM = Cus.[Division ID]
Left JOIN #tempSalesTarget te on cu.ACCOUNTNUM=te.CUSTACCOUNT
and te.Division=Cus.[Division ID]
and cu.SALESGROUP=te.SALESUNITID
left JOIN #tempSalesEngineers tes ON cu.SALESGROUP=tes.SALESUNITID and (te.SALESMANID = tes.SALESMANID or te.SalesManID IS NULL)
LEFT OUTER JOIN #tempCustIndustry ON cu.ACCOUNTNUM = #tempCustIndustry.ACCOUNTNUM
where IsNull(tes.SALESMANID,'') IN (#SalesEngineer)
AND cu.[dimension2_] in (#dimension)
GROUP BY
d1.[DESCRIPTION],
d2.[DESCRIPTION],
d1.NUM,
d2.NUM,
cu.[NAME],
cu.[ACCOUNTNUM],
BUSINESSSECTORID,
cu.[STREET],
cu.[CITY],
cu.[STATE],
cu.[ZIPCODE],
cu.[SalesGroup],
[Sales Engineer],
tes.SALESMANID,
[Projection],
[Year Goal],
[YTD Projection],
[PROJECTION COMMENT],
backlog
I am getting two different results for each entry:
How can I get the rows to match up? the fields for the first query are invalid in the second query

I could be wrong, but it appears your columns dont match... your first query has a column
ISNULL(#tempBacklog.CUSTACCOUNT, #tempCompleteNotInvoiced.CUSTACCOUNT) AS 'accountnum'
but there is no corresponding (last column in the second query). A union needs to be same columns, data types and order. I think it was just an oversight. For grins, even if in the second query you add
'test' as 'accountnum'
just to confirm, see what happens / if it goes through.
ADDITIONALLY, the last column of your second query looks cut short via...
SUM([Completed Not Invoiced]) AS 'Completed Not Invoiced'
) as Cus on (cu.ACCOUNTNUM = Cus.ACCOUNTNUM)
As menstioned, no 'accountnum' column to match the first query, but also not seeing a "FROM" clause and it's initial table before the JOIN. Again. maybe I'm missing something, but the formatting of the query is not quite there.
I have reformatted the query some for readability from your original. I changed some of the long #temp aliases to abbreviated for readability purposes.
SELECT
ISNULL(tBL.Division, #tempCompleteNotInvoiced.Division) AS 'Division',
'NONE' as 'Division ID',
'NONE' as 'NAME',
'NONE' AS 'Sales Engineer',
0.00 As 'Current MTD SALES',
0.00 As 'Last Year MTD SALES',
0.00 as 'Projected MTD Sales',
ISNULL(Backlog, 0) AS 'Backlog',
ISNULL([Complete Not Invoiced], 0) AS 'Completed Not Invoiced',
ISNULL(tBL.CUSTACCOUNT, #tempCompleteNotInvoiced.CUSTACCOUNT) AS 'accountnum'
FROM
#tempBacklog tBL
FULL OUTER JOIN #tempCompleteNotInvoiced
ON tBL.ITEMGROUPID = tCNI.ITEMGROUPID
AND tBL.Division = tCNI.Division
AND tBL.[Ledger Account] = tCNI.[Ledger Account]
AND tBL.CUSTACCOUNT = tCNI.CUSTACCOUNT
union all
select
Division,
[Division ID],
[NAME],
CASE WHEN IsNull([Sales Engineer],'')=''
Then Division+'-UnKnown'
ELSE [Sales Engineer] END AS 'Sales Engineer',
(case WHEN MONTH(GETDATE()) = 1 then SUM([1])
WHEN MONTH(GETDATE()) = 2 then SUM([2])
WHEN MONTH(GETDATE()) = 3 THEN SUM([3])
WHEN MONTH(GETDATE()) = 4 THEN SUM([4])
WHEN MONTH(GETDATE()) = 5 THEN SUM([5])
WHEN MONTH(GETDATE()) = 6 THEN SUM([6])
WHEN MONTH(GETDATE()) = 7 THEN SUM([7])
WHEN MONTH(GETDATE()) = 8 THEN SUM([8])
WHEN MONTH(GETDATE()) = 9 THEN SUM([9])
WHEN MONTH(GETDATE()) = 10 THEN SUM([10])
WHEN MONTH(GETDATE()) = 11 THEN SUM([11])
WHEN MONTH(GETDATE()) = 12 THEN SUM([12])
END) As 'Current MTD SALES',
(case WHEN MONTH(GETDATE()) = 1 then SUM([L1])
WHEN MONTH(GETDATE()) = 2 then SUM([L2])
WHEN MONTH(GETDATE()) = 3 THEN SUM([L3])
WHEN MONTH(GETDATE()) = 4 THEN SUM([L4])
WHEN MONTH(GETDATE()) = 5 THEN SUM([L5])
WHEN MONTH(GETDATE()) = 6 THEN SUM([L6])
WHEN MONTH(GETDATE()) = 7 THEN SUM([L7])
WHEN MONTH(GETDATE()) = 8 THEN SUM([L8])
WHEN MONTH(GETDATE()) = 9 THEN SUM([L9])
WHEN MONTH(GETDATE()) = 10 THEN SUM([L10])
WHEN MONTH(GETDATE()) = 11 THEN SUM([L11])
WHEN MONTH(GETDATE()) = 12 THEN SUM([L12])
END) As 'Last Year MTD SALES',
(case WHEN MONTH(GETDATE()) = 1 then SUM([YTD1])
WHEN MONTH(GETDATE()) = 2 then SUM([YTD2])
WHEN MONTH(GETDATE()) = 3 THEN SUM([YTD3])
WHEN MONTH(GETDATE()) = 4 THEN SUM([YTD4])
WHEN MONTH(GETDATE()) = 5 THEN SUM([YTD5])
WHEN MONTH(GETDATE()) = 6 THEN SUM([YTD6])
WHEN MONTH(GETDATE()) = 7 THEN SUM([YTD7])
WHEN MONTH(GETDATE()) = 8 THEN SUM([YTD8])
WHEN MONTH(GETDATE()) = 9 THEN SUM([YTD9])
WHEN MONTH(GETDATE()) = 10 THEN SUM([YTD10])
WHEN MONTH(GETDATE()) = 11 THEN SUM([YTD11])
WHEN MONTH(GETDATE()) = 12 THEN SUM([YTD12])
END) as 'Projected MTD Sales',
SUM(Backlog) AS 'Backlog',
SUM([Completed Not Invoiced]) AS 'Completed Not Invoiced',
accountnum
from
( select
IsNULL([DESCRIPTION],'None') as Division,
LT.[DIMENSION2_] AS 'Division ID',
'NONE' as 'NAME',
'NONE' as 'ACCOUNTNUM',
'NONE' AS 'Industry',
'NONE' as 'Street',
'NONE' as 'City',
'NONE' as 'State',
'NONE' as 'ZipCode',
'' as 'Sales Engineer',
'NONE' as 'SalesGroup',
'' as 'SALESMANID',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #1Start AND #YTD THEN LT.[AMOUNTMST] ELSE 0 END) AS 'YTD Sales',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #1Start AND #1End THEN LT.[AMOUNTMST] ELSE 0 END) AS '1',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #2Start AND #2End THEN LT.[AMOUNTMST] ELSE 0 END) AS '2',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #3Start AND #3End THEN LT.[AMOUNTMST] ELSE 0 END) AS '3',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #4Start AND #4End THEN LT.[AMOUNTMST] ELSE 0 END) AS '4',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #5Start AND #5End THEN LT.[AMOUNTMST] ELSE 0 END) AS '5',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #6Start AND #6End THEN LT.[AMOUNTMST] ELSE 0 END) AS '6',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #7Start AND #7End THEN LT.[AMOUNTMST] ELSE 0 END) AS '7',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #8Start AND #8End THEN LT.[AMOUNTMST] ELSE 0 END) AS '8',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #9Start AND #9End THEN LT.[AMOUNTMST] ELSE 0 END) AS '9',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #10Start AND #10End THEN LT.[AMOUNTMST] ELSE 0 END) AS '10',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #11Start AND #11End THEN LT.[AMOUNTMST] ELSE 0 END) AS '11',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #12Start AND #12End THEN LT.[AMOUNTMST] ELSE 0 END) AS '12',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #LYTD_Start AND #LYTD_End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'Last YTD Sales',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #LYS_Start AND #LYS_End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'Last Year Sales',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L1Start AND #L1End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L1',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L2Start AND #L2End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L2',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L3Start AND #L3End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L3',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L4Start AND #L4End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L4',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L5Start AND #L5End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L5',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L6Start AND #L6End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L6',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L7Start AND #L7End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L7',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L8Start AND #L8End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L8',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L9Start AND #L9End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L9',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L10Start AND #L10End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L10',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L11Start AND #L11End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L11',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L12Start AND #L12End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L12',
0.00 as 'Projection',
0.00 AS 'YTD Projection',
0.00 AS 'YTD1',
0.00 AS 'YTD2',
0.00 AS 'YTD3',
0.00 AS 'YTD4',
0.00 AS 'YTD5',
0.00 AS 'YTD6',
0.00 AS 'YTD7',
0.00 AS 'YTD8',
0.00 AS 'YTD9',
0.00 AS 'YTD10',
0.00 AS 'YTD11',
0.00 AS 'YTD12',
0.00 as 'Year Goal',
'' as 'PROJECTION COMMENT',
0.00 AS 'Backlog',
0.00 AS 'Completed Not Invoiced'
from
dbo.[LedgerTrans] LT
inner Join dbo.[LedgerJournalTrans] LJ
on LT.Voucher = LJ.Voucher
and LT.TransDate = LJ.TransDate
and AccountType = '0'
and LT.ACCOUNTNUM = LJ.ACCOUNTNUM
and LT.DIMENSION2_ = LJ.DIMENSION2_
and LT.AMOUNTMST = (CASE WHEN AMOUNTCURDEBIT != 0
then AMOUNTCURDEBIT
else -1 * AMOUNTCURCREDIT END)
Inner JOIN dbo.DIMENSIONS
ON LT.DIMENSION2_ = NUM
Inner Join dbo.LedgerTable LD
ON LT.ACCOUNTNUM = LD.ACCOUNTNUM
AND LJ.ACCOUNTNUM = LD.ACCOUNTNUM
where
( #reportType = 'Forecasting'
and LJ.ACCOUNTNUM between '400100' and '409400'
and LT.ACCOUNTNUM between '400100' and '409400'
and LJ.DocumentNum = ''
and LT.[DIMENSION2_] != '10'
and LD.KTI_OASALESCOMM = 0
AND LT.[DIMENSION2_] in (#dimension))
OR
( #reportType = 'Financial'
and LJ.DocumentNum = ''
and LT.[DIMENSION2_] != '10'
and LJ.ACCOUNTNUM between '400100' and '409400'
and LT.ACCOUNTNUM between '400100' and '409400'
AND LT.[DIMENSION2_] in (#dimension))
group by
[DESCRIPTION],
LT.[DIMENSION2_]
UNION ALL
SELECT
IsNULL(ISNULL(NULLIF(d2.[DESCRIPTION], ''), d1.[DESCRIPTION]),'None') as Division,
IsNULL(ISNULL(NULLIF(d2.NUM, ''), d1.NUM),'None') as 'Division ID',
cu.[NAME] as 'NAME',
cu.[ACCOUNTNUM] as 'ACCOUNTNUM',
BUSINESSSECTORID AS 'Industry',
cu.[STREET] as 'Street',
cu.[CITY] as 'City',
cu.[STATE] as 'State',
cu.[ZIPCODE] as 'ZipCode',
[Sales Engineer] as 'Sales Engineer',
cu.[SalesGroup] as 'SalesGroup',
IsNull(tes.SALESMANID,'') as 'SALESMANID',
SUM([YTD Sales]) as 'YTD Sales',
SUM([1]) as '1',
SUM([2]) as '2',
SUM([3]) as '3',
SUM([4]) as '4',
SUM([5]) as '5',
SUM([6]) as '6',
SUM([7]) as '7',
SUM([8]) as '8',
SUM([9]) as '9',
SUM([10]) as '10',
SUM([11]) as '11',
SUM([12]) as '12',
SUM([Last YTD Sales]) as 'Last YTD Sales',
SUM([Last Year Sales]) as 'Last Year Sales',
SUM([L1]) as 'L1',
SUM([L2]) as 'L2',
SUM([L3]) as 'L3',
SUM([L4]) as 'L4',
SUM([L5]) as 'L5',
SUM([L6]) as 'L6',
SUM([L7]) as 'L7',
SUM([L8]) as 'L8',
SUM([L9]) as 'L9',
SUM([L10]) as 'L10',
SUM([L11]) as 'L11',
SUM([L12]) as 'L12',
IsNULL(Projection,0.00) as 'Projection',
[YTD Projection] as 'YTD Projection',
ISNULL( ( Select Top(1) [YTD Projection]
from #tempSalesTargetMW
where STARTDATE >= #1YTDStart
and ENDDATE <= #1YTDEnd
and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL( ISNULL( NULLIF(d2.NUM,null), d1.NUM),null )
and SalesUnitId = cu.[SalesGroup] ), 0) AS 'YTD1',
ISNULL( ( Select Top(1) [YTD Projection]
from #tempSalesTargetMW
where STARTDATE> = #2YTDStart
and ENDDATE <= #2YTDEnd
and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL( ISNULL( NULLIF(d2.NUM,null), d1.NUM), null )
and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD2',
ISNULL( ( Select Top(1) [YTD Projection]
from #tempSalesTargetMW
where STARTDATE >= #3YTDStart
and ENDDATE <= #3YTDEnd
and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL( ISNULL( NULLIF(d2.NUM,null), d1.NUM),null)
and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD3',
ISNULL( ( Select Top(1) [YTD Projection]
from #tempSalesTargetMW
where STARTDATE >= #4YTDStart
and ENDDATE <= #4YTDEnd
and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL( ISNULL( NULLIF(d2.NUM,null), d1.NUM),null)
and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD4',
ISNULL( ( Select Top(1) [YTD Projection]
from #tempSalesTargetMW
where STARTDATE >= #5YTDStart
and ENDDATE <= #5YTDEnd
and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null)
and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD5',
ISNULL( ( Select Top(1) [YTD Projection]
from #tempSalesTargetMW
where STARTDATE >= #6YTDStart
and ENDDATE <= #6YTDEnd
and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null)
and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD6',
ISNULL( ( Select Top(1) [YTD Projection]
from #tempSalesTargetMW
where STARTDATE >= #7YTDStart
and ENDDATE <= #7YTDEnd
and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null)
and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD7',
ISNULL( ( Select Top(1)[YTD Projection]
from #tempSalesTargetMW
where STARTDATE >= #8YTDStart
and ENDDATE <= #8YTDEnd
and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null)
and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD8',
ISNULL( ( Select Top(1) [YTD Projection]
from #tempSalesTargetMW
where STARTDATE >= #9YTDStart
and ENDDATE <= #9YTDEnd
and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null)
and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD9',
ISNULL( ( Select Top(1) [YTD Projection]
from #tempSalesTargetMW
where STARTDATE >= #10YTDStart
and ENDDATE <= #10YTDEnd
and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null)
and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD10',
ISNULL( ( Select Top(1) [YTD Projection]
from #tempSalesTargetMW
where STARTDATE >= #11YTDStart
and ENDDATE <= #11YTDEnd
and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null)
and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD11',
ISNULL( ( Select Top(1) [YTD Projection]
from #tempSalesTargetMW
where STARTDATE >= #12YTDStart
and ENDDATE <= #12YTDEnd
and CUSTACCOUNT = cu.[ACCOUNTNUM]
and Division = IsNULL(ISNULL(NULLIF(d2.NUM,null), d1.NUM),null)
and SalesUnitId = cu.[SalesGroup]),0) AS 'YTD12',
[Year Goal] as 'Year Goal',
[PROJECTION COMMENT],
0.00 AS 'Backlog',
0.00 AS 'Completed Not Invoiced'
from
[CUSTTABLE] cu
Left JOIN ( select
LT.[DIMENSION2_] AS 'Division ID',
LJ.ACCOUNTNUM as 'ACCOUNTNUM',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #1Start AND #YTD THEN LT.[AMOUNTMST] ELSE 0 END) AS 'YTD Sales',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #1Start AND #1End THEN LT.[AMOUNTMST] ELSE 0 END) AS '1',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #2Start AND #2End THEN LT.[AMOUNTMST] ELSE 0 END) AS '2',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #3Start AND #3End THEN LT.[AMOUNTMST] ELSE 0 END) AS '3',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #4Start AND #4End THEN LT.[AMOUNTMST] ELSE 0 END) AS '4',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #5Start AND #5End THEN LT.[AMOUNTMST] ELSE 0 END) AS '5',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #6Start AND #6End THEN LT.[AMOUNTMST] ELSE 0 END) AS '6',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #7Start AND #7End THEN LT.[AMOUNTMST] ELSE 0 END) AS '7',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #8Start AND #8End THEN LT.[AMOUNTMST] ELSE 0 END) AS '8',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #9Start AND #9End THEN LT.[AMOUNTMST] ELSE 0 END) AS '9',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #10Start AND #10End THEN LT.[AMOUNTMST] ELSE 0 END) AS '10',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #11Start AND #11End THEN LT.[AMOUNTMST] ELSE 0 END) AS '11',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #12Start AND #12End THEN LT.[AMOUNTMST] ELSE 0 END) AS '12',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #LYTD_Start AND #LYTD_End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'Last YTD Sales',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #LYS_Start AND #LYS_End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'Last Year Sales',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L1Start AND #L1End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L1',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L2Start AND #L2End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L2',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L3Start AND #L3End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L3',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L4Start AND #L4End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L4',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L5Start AND #L5End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L5',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L6Start AND #L6End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L6',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L7Start AND #L7End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L7',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L8Start AND #L8End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L8',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L9Start AND #L9End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L9',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L10Start AND #L10End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L10',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L11Start AND #L11End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L11',
-1 * SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L12Start AND #L12End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L12',
LT.[TRANSDATE],
0.00 AS 'Backlog',
0.00 AS 'Completed Not Invoiced'
from
dbo.[LedgerTrans] LT
inner JOIN dbo.[LedgerJournalTrans] LJ
on LT.Voucher = LJ.Voucher
and LT.TransDate = LJ.TransDate
and AccountType in ('1')
Inner Join dbo.LedgerTable LD
on LT.ACCOUNTNUM = LD.ACCOUNTNUM
where
LT.ACCOUNTNUM between '400100' and '409400'
AND LT.[TRANSDATE] BETWEEN #LYS_Start AND #12End
and LT.[DIMENSION2_] = '10'
and LT.Voucher Not Like 'JE%'
and LD.KTI_OASALESCOMM = 0
AND LT.[DIMENSION2_] in (#dimension)
and #reportType='Forecasting'
or
( LT.[TRANSDATE] BETWEEN #LYS_Start AND #12End
and LT.[DIMENSION2_] = '10'
and LT.Voucher Not Like 'JE%'
AND LT.ACCOUNTNUM between '400100' and '409400'
AND LT.[DIMENSION2_] in (#dimension)
and #reportType='Financial')
group by
LJ.ACCOUNTNUM,
LT.[DIMENSION2_],
LT.[TRANSDATE]
union all
select
LT.[DIMENSION2_] AS 'Division ID',
LJ.ACCOUNTNUM as 'ACCOUNTNUM',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #1Start AND #YTD THEN LT.[AMOUNTMST] ELSE 0 END) AS 'YTD Sales',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #1Start AND #1End THEN LT.[AMOUNTMST] ELSE 0 END) AS '1',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #2Start AND #2End THEN LT.[AMOUNTMST] ELSE 0 END) AS '2',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #3Start AND #3End THEN LT.[AMOUNTMST] ELSE 0 END) AS '3',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #4Start AND #4End THEN LT.[AMOUNTMST] ELSE 0 END) AS '4',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #5Start AND #5End THEN LT.[AMOUNTMST] ELSE 0 END) AS '5',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #6Start AND #6End THEN LT.[AMOUNTMST] ELSE 0 END) AS '6',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #7Start AND #7End THEN LT.[AMOUNTMST] ELSE 0 END) AS '7',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #8Start AND #8End THEN LT.[AMOUNTMST] ELSE 0 END) AS '8',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #9Start AND #9End THEN LT.[AMOUNTMST] ELSE 0 END) AS '9',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #10Start AND #10End THEN LT.[AMOUNTMST] ELSE 0 END) AS '10',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #11Start AND #11End THEN LT.[AMOUNTMST] ELSE 0 END) AS '11',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #12Start AND #12End THEN LT.[AMOUNTMST] ELSE 0 END) AS '12',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #LYTD_Start AND #LYTD_End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'Last YTD Sales',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #LYS_Start AND #LYS_End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'Last Year Sales',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L1Start AND #L1End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L1',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L2Start AND #L2End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L2',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L3Start AND #L3End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L3',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L4Start AND #L4End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L4',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L5Start AND #L5End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L5',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L6Start AND #L6End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L6',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L7Start AND #L7End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L7',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L8Start AND #L8End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L8',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L9Start AND #L9End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L9',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L10Start AND #L10End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L10',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L11Start AND #L11End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L11',
-1*SUM(CASE WHEN LT.[TRANSDATE] BETWEEN #L12Start AND #L12End THEN LT.[AMOUNTMST] ELSE 0 END) AS 'L12',
LT.[TRANSDATE],
0.00 AS 'Backlog',
0.00 AS 'Completed Not Invoiced'
from
dbo.[LedgerTrans] LT
inner JOIN dbo.[LedgerJournalTrans] LJ
on LT.Voucher = LJ.Voucher
and LT.TransDate = LJ.TransDate
and AccountType in ('1')
Inner Join dbo.LedgerTable LD
on LT.ACCOUNTNUM = LD.ACCOUNTNUM
where
LT.ACCOUNTNUM between '400100' and '409400'
AND LT.[TRANSDATE] BETWEEN #LYS_Start AND #12End
and LT.[DIMENSION2_] != '10'
and LD.KTI_OASALESCOMM = 0
and #reportType = 'Forecasting'
AND LT.[DIMENSION2_] in (#dimension)
OR
( LT.[TRANSDATE] BETWEEN #LYS_Start AND #12End
and LT.[DIMENSION2_] != '10'
and #reportType = 'Financial'
AND LT.ACCOUNTNUM between '400100' and '409400'
AND LT.[DIMENSION2_] in (#dimension) )
group by
LJ.ACCOUNTNUM,
LT.[DIMENSION2_],
LT.[TRANSDATE] ) as Cus
on cu.ACCOUNTNUM = Cus.ACCOUNTNUM
Inner JOIN dbo.DIMENSIONS d1
ON cu.[dimension2_] = NUM
LEFT OUTER JOIN dbo.DIMENSIONS
d2 ON Cus.[Division ID] = d2.NUM
Left JOIN #tempSalesTarget te
on cu.ACCOUNTNUM = te.CUSTACCOUNT
and te.Division = Cus.[Division ID]
and cu.SALESGROUP = te.SALESUNITID
left JOIN #tempSalesEngineers tes
ON cu.SALESGROUP = tes.SALESUNITID
and (te.SALESMANID = tes.SALESMANID or te.SalesManID IS NULL)
LEFT OUTER JOIN #tempCustIndustry
ON cu.ACCOUNTNUM = #tempCustIndustry.ACCOUNTNUM
where
IsNull(tes.SALESMANID,'') IN (#SalesEngineer)
AND cu.[dimension2_] in (#dimension)
GROUP BY
d1.[DESCRIPTION],
d2.[DESCRIPTION],
d1.NUM,
d2.NUM,
cu.[NAME],
cu.[ACCOUNTNUM],
BUSINESSSECTORID,
cu.[STREET],
cu.[CITY],
cu.[STATE],
cu.[ZIPCODE],
cu.[SalesGroup],
[Sales Engineer],
tes.SALESMANID,
[Projection],
[Year Goal],
[YTD Projection],
[PROJECTION COMMENT],
backlog
Now, in the lower queries where you are doing the "cu" and "cus" select/unions, you have some where clauses like...
where
( LT.ACCOUNTNUM between '400100' and '409400')
AND LT.[TRANSDATE] BETWEEN #LYS_Start AND #12End
and LT.[DIMENSION2_] = '10'
and LT.Voucher Not Like 'JE%'
and LD.KTI_OASALESCOMM = 0
AND LT.[DIMENSION2_] in (#dimension)
and #reportType='Forecasting'
or
( LT.[TRANSDATE] BETWEEN #LYS_Start AND #12End
and LT.[DIMENSION2_] = '10'
and LT.Voucher Not Like 'JE%'
AND LT.ACCOUNTNUM between '400100' and '409400'
AND LT.[DIMENSION2_] in (#dimension)
and #reportType='Financial' )
Is that what you expected (for both instances), or should it have been
where
( first set of criteria )
OR
( second set of criteria )
But could be simplified down to...
where
LT.ACCOUNTNUM between '400100' and '409400'
AND LT.[TRANSDATE] BETWEEN #LYS_Start AND #12End
and LT.[DIMENSION2_] = '10'
and LT.Voucher Not Like 'JE%'
AND LT.[DIMENSION2_] in (#dimension)
and ( ( LD.KTI_OASALESCOMM = 0
and #reportType='Forecasting' )
or
#reportType='Financial'
)

Related

troubles with error: Divide by zero error encountered

Hello two days I have tried to figure out why my code isn't working.
I am quite sure that it's a stupid mistake, but if anybody has time to check the code I would really appreciate.
I have tried to comment out this "SUM" case, but then everything else breaks
I know that this line screws with me, but I can't figure out how to fix this:
sum (Case when bm.CaseQTY IS NULL
then (k.postedqty / mm.CaseQTY)
else (k.postedqty / bm.CaseQTY)
End) as laoseiskaste,
sum (Case when bm.CaseQTY IS NULL
then ((k.postedqty-k.reservordered-k.reservphysical-k.picked+k.registered) / mm.CaseQTY)
else ((k.postedqty-k.reservordered-k.reservphysical-k.picked+k.registered) / bm.CaseQTY)
End) as vabakaste
from (select s.itemid, i.product, i.ItemMiscRefId, i.MMFItemProductGroupId, s.INVENTDIMID,
s.postedqty, s.registered, s.reservordered, s.reservphysical, s.picked, s.ordered,
s.postedvalue, s.received, i.PrimaryVendorId, i.standardPalletQuantity
from inventsum s WITH (INDEX(I_174CLOSEDITEMDIMIDX),NOLOCK),
SELECT k.itemid AS itemid,
(CASE WHEN ISNULL(bm.mmfitemid, '') != '' THEN bm.mmfitemid ELSE mm.mmfitemid END) AS mmfitemid,
(CASE WHEN ISNULL(bm.itembarcode, '') != '' THEN bm.itembarcode ELSE mm.itembarcode END) AS itembarcode,
e.name AS name, d.inventlocationid AS inventlocationid, d.inventbatchid AS inventbatchid,
LEFT(CONVERT(varchar, ib.proddate, 121), 10) AS proddate,
LEFT(CONVERT(varchar, ib.expdate, 121), 10) AS expdate,
d.wmslocationid AS wmslocationid, d.wmspalletid AS wmspalletid, p.pallettypeid AS pallettypeid,
xz.inputblockingcauseid AS inputblockingcauseid, xz.outputblockingcauseid AS outputblockingcauseid,
d.inventserialid AS inventserialid, d.inventownerid_via AS inventownerid_via,
d.inventlabelid_via AS inventlabelid_via, d.inventtaxstampid AS inventtaxstampid,
(CASE WHEN ISNULL(bm.CaseQTY, 0) != 0 THEN bm.CaseQTY ELSE mm.CaseQTY END) AS caseqty,
k.standardPalletQuantity AS palletqty,
(CASE WHEN ISNULL(bm.caseheight, 0) != 0 THEN bm.caseheight ELSE mm.caseheight END) AS caseheight,
(CASE WHEN ISNULL(bm.casewidth, 0) != 0 THEN bm.casewidth ELSE mm.casewidth END) AS casewidth,
(CASE WHEN ISNULL(bm.casedepth, 0) != 0 THEN bm.casedepth ELSE mm.casedepth END) AS casedepth,
(CASE WHEN ISNULL(bm.casebarcode, '') != '' THEN bm.casebarcode ELSE mm.casebarcode END) AS casebarcode,
(CASE WHEN ISNULL(bm.casebrutoweight, 0) != 0 THEN bm.casebrutoweight ELSE mm.casebrutoweight END) AS casebrutoweight,
(CASE WHEN ISNULL(bm.alcopct, 0) != 0 THEN bm.alcopct ELSE mm.alcopct END) AS alcopct,
(CASE WHEN ISNULL(bm.blockqty, 0) != 0 THEN bm.blockqty ELSE mm.blockqty END) AS blockqty,
(CASE WHEN ISNULL(bm.exciseproductregnum, '') != ''
THEN bm.exciseproductregnum
ELSE mm.exciseproductregnum
END) AS exciseproductregnum,
SUM(k.postedqty + k.received + k.registered) AS postedqty,
SUM(k.registered) AS registeredqty,
SUM(k.reservordered + k.reservphysical) AS reservedqty, SUM(k.picked) AS pickedqty,
SUM(k.postedqty - k.reservordered - k.reservphysical - k.picked + k.registered) AS freeqty,
SUM(k.ordered) AS ordered, SUM(k.postedvalue) AS postedvalue,
k.MMFItemProductGroupId AS mmfitemproductgroupid,
SUM(CASE WHEN bm.CaseQTY IS NULL
THEN (k.postedqty / mm.CaseQTY)
ELSE (k.postedqty / bm.CaseQTY)
END) AS laoseiskaste,
SUM(CASE WHEN bm.CaseQTY IS NULL
THEN ((k.postedqty - k.reservordered - k.reservphysical - k.picked + k.registered) / mm.CaseQTY)
ELSE ((k.postedqty - k.reservordered - k.reservphysical - k.picked + k.registered) / bm.CaseQTY)
END) AS vabakaste
FROM (SELECT s.itemid, i.product, i.ItemMiscRefId, i.MMFItemProductGroupId, s.INVENTDIMID,
s.postedqty, s.registered, s.reservordered, s.reservphysical, s.picked,
s.ordered, s.postedvalue, s.received, i.PrimaryVendorId, i.standardPalletQuantity
FROM inventsum s WITH (INDEX(I_174CLOSEDITEMDIMIDX), NOLOCK),
inventtable i WITH (INDEX([I_175ITEMIDX]), NOLOCK)
WHERE s.itemid = i.itemid
AND s.DATAAREAID = #Var1
AND i.DATAAREAID = #Var1
AND s.PARTITION = 5637144576
AND i.PARTITION = 5637144576
AND RIGHT(s.ITEMID, 2) = 'LA'
AND s.CLOSED = 0
AND (s.POSTEDQTY != 0
OR s.reservordered + s.reservphysical != 0
OR s.ordered != 0
)
) k
JOIN inventdim d WITH (INDEX(I_698DIMIDIDX), NOLOCK)
ON (k.INVENTDIMID = d.INVENTDIMID
AND d.DATAAREAID = #Var3
AND d.PARTITION = 5637144576)
LEFT OUTER JOIN EcoresProductTranslation e WITH (INDEX(I_6869PRODUCTLANGUAGEIDX))
ON (k.product = e.product
AND e.languageid = 'et'
AND e.PARTITION = 5637144576)
LEFT OUTER JOIN WMSPALLET p
ON (p.WMSPALLETID = d.WMSPALLETID
AND p.PARTITION = 5637144576
AND p.DATAAREAID = #Var4)
LEFT OUTER JOIN InventItemMisc mm WITH (INDEX(I_103616RecId))
ON (mm.RecId = k.ItemMiscRefId
AND mm.PARTITION = 5637144576)
LEFT OUTER JOIN InventBatch ib WITH (INDEX(I_752itemBatchIdx))
ON (ib.ItemId = k.ItemId
AND ib.InventBatchId = d.InventBatchId
AND ib.PARTITION = 5637144576
AND ib.DATAAREAID = #Var5)
LEFT OUTER JOIN InventItemMisc bm WITH (INDEX(I_103616RecId))
ON (bm.RecId = ib.ItemMiscRefId
AND bm.PARTITION = 5637144576)
JOIN WMSLOCATIOn xz WITH (INDEX(/*I672COORDINATEDIDX*/ I_672LOCATIONIDX))
ON (xz.inventlocationID = d.inventlocationID
AND xz.wmslocationid = d.wmslocationid
AND xz.partition = 5637144576
AND xz.dataareaid = 'EWH')
WHERE 1 = 1
GROUP BY k.itemid,
(CASE WHEN ISNULL(bm.mmfitemid, '') != '' THEN bm.mmfitemid ELSE mm.mmfitemid END),
(CASE WHEN ISNULL(bm.itembarcode, '') != '' THEN bm.itembarcode ELSE mm.itembarcode END),
e.name, d.inventlocationid, d.inventbatchid, LEFT(CONVERT(varchar, ib.proddate, 121), 10),
LEFT(CONVERT(varchar, ib.expdate, 121), 10), d.wmslocationid, d.wmspalletid,
p.pallettypeid, xz.inputblockingcauseid, xz.outputblockingcauseid, d.inventserialid,
d.inventownerid_via, d.inventlabelid_via, d.inventtaxstampid,
(CASE WHEN ISNULL(bm.CaseQTY, 0) != 0 THEN bm.CaseQTY ELSE mm.CaseQTY END),
k.standardPalletQuantity,
(CASE WHEN ISNULL(bm.caseheight, 0) != 0 THEN bm.caseheight ELSE mm.caseheight END),
(CASE WHEN ISNULL(bm.casewidth, 0) != 0 THEN bm.casewidth ELSE mm.casewidth END),
(CASE WHEN ISNULL(bm.casedepth, 0) != 0 THEN bm.casedepth ELSE mm.casedepth END),
(CASE WHEN ISNULL(bm.casebarcode, '') != '' THEN bm.casebarcode ELSE mm.casebarcode END),
(CASE WHEN ISNULL(bm.casebrutoweight, 0) != 0 THEN bm.casebrutoweight ELSE mm.casebrutoweight END),
(CASE WHEN ISNULL(bm.alcopct, 0) != 0 THEN bm.alcopct ELSE mm.alcopct END),
(CASE WHEN ISNULL(bm.blockqty, 0) != 0 THEN bm.blockqty ELSE mm.blockqty END),
(CASE WHEN ISNULL(bm.exciseproductregnum, '') != ''
THEN bm.exciseproductregnum
ELSE mm.exciseproductregnum
END),
k.MMFItemProductGroupId
ORDER BY k.itemid,
(CASE WHEN ISNULL(bm.mmfitemid, '') != '' THEN bm.mmfitemid ELSE mm.mmfitemid END),
(CASE WHEN ISNULL(bm.itembarcode, '') != '' THEN bm.itembarcode ELSE mm.itembarcode END),
e.name, d.inventlocationid, d.inventbatchid, LEFT(CONVERT(varchar, ib.proddate, 121), 10),
LEFT(CONVERT(varchar, ib.expdate, 121), 10), d.wmslocationid, d.wmspalletid,
p.pallettypeid, xz.inputblockingcauseid, xz.outputblockingcauseid,
d.inventserialid, d.inventownerid_via, d.inventlabelid_via, d.inventtaxstampid,
(CASE WHEN ISNULL(bm.CaseQTY, 0) != 0 THEN bm.CaseQTY ELSE mm.CaseQTY END),
k.standardPalletQuantity,
(CASE WHEN ISNULL(bm.caseheight, 0) != 0 THEN bm.caseheight ELSE mm.caseheight END),
(CASE WHEN ISNULL(bm.casewidth, 0) != 0 THEN bm.casewidth ELSE mm.casewidth END),
(CASE WHEN ISNULL(bm.casedepth, 0) != 0 THEN bm.casedepth ELSE mm.casedepth END),
(CASE WHEN ISNULL(bm.casebarcode, '') != '' THEN bm.casebarcode ELSE mm.casebarcode END),
(CASE WHEN ISNULL(bm.casebrutoweight, 0) != 0 THEN bm.casebrutoweight ELSE mm.casebrutoweight END),
(CASE WHEN ISNULL(bm.alcopct, 0) != 0 THEN bm.alcopct ELSE mm.alcopct END),
(CASE WHEN ISNULL(bm.blockqty, 0) != 0 THEN bm.blockqty ELSE mm.blockqty END),
(CASE WHEN ISNULL(bm.exciseproductregnum, '') != ''
THEN bm.exciseproductregnum
ELSE mm.exciseproductregnum
END),
k.MMFItemProductGroupId;
Error in SQL:Error in SQL:[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Divide by zero error encountered.
In SSMS, hit Ctrl+F to open the Find & Replace dialogue box. Search the query for all instances of /. This will tell you everywhere that division is happening, plus some false positives.
In every single instance, the query is dividing by mm.CaseQTY or bm.CaseQTY. Those are the only two values, and the only two tables you have to worry about. One or the other of them is coming through as a zero.
We don't have access to your database, so we can't help you troubleshoot the data issue, but that's how I'd go about deciding where to start looking.

How do I replace null with 0 in SUM CASE WHEN statement?

I am using a CASE WHEN statement and a SUM function. I want to replace all nulls with 0.
I tried adding a 0 at the end of my statement.
This is my current code
select ID, PT_Number,
ORGANIZATION,
[Approved] = sum(case when PT_TYPE = 'Lend' then Approved END),
[Disbursed] = sum(case when PT_TYPE = 'Give' then Disbursed end),
[Repaid] = sum(case when PT_TYPE = 'Pay' then Payment end)
from TABLE1
group by ID, PT_Number,
ORGANIZATION
This is what I am trying
[Approved] = sum(case when PT_TYPE = 'Lend' then Approved END, 0),
[Disbursed] = sum(case when PT_TYPE = 'Give' then Disbursed end, 0),
[Repaid] = sum(case when PT_TYPE = 'Pay' then Payment end, 0)
Just add an else clause:
select ID, PT_Number,
ORGANIZATION,
[Approved] = sum(case when PT_TYPE = 'Lend' then Approved else 0 END),
[Disbursed] = sum(case when PT_TYPE = 'Give' then Disbursed else 0 end),
[Repaid] = sum(case when PT_TYPE = 'Pay' then Payment else 0 end)
from TABLE1
group by ID, PT_Number, ORGANIZATION;
You could also use coalesce() but that seems like overkill.

Need Multiple Values from Single Column

I am trying to join these two tables, or use a sub-query to achieve the results I need.
As of now I have the first query pulling hourly totals with a overall total between MIN(time) and MAX(time). I need to join the second query to get the total scans from MIN(time) and MAX(time)
Any ideas of where I could be going wrong?
select
UPPER(t.operator) as Operator,
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 6 THEN 1 ELSE 0 END)) ELSE NULL END AS '6AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 7 THEN 1 ELSE 0 END)) ELSE NULL END AS '7AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 8 THEN 1 ELSE 0 END)) ELSE NULL END AS '8AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 9 THEN 1 ELSE 0 END)) ELSE NULL END AS '9AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 10 THEN 1 ELSE 0 END)) ELSE NULL END AS '10AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 11 THEN 1 ELSE 0 END)) ELSE NULL END AS '11AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 12 THEN 1 ELSE 0 END)) ELSE NULL END AS '12PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 13 THEN 1 ELSE 0 END)) ELSE NULL END AS '1PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 14 THEN 1 ELSE 0 END)) ELSE NULL END AS '2PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 15 THEN 1 ELSE 0 END)) ELSE NULL END AS '3PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 16 THEN 1 ELSE 0 END)) ELSE NULL END AS '4PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 17 THEN 1 ELSE 0 END)) ELSE NULL END AS '5PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (COUNT(CASE WHEN DATEPART(HOUR,t.time) > 17 THEN t.eventtype ELSE NULL END)) ELSE NULL END AS '6+PM',
SUM(CASE WHEN t.eventtype = 'Replenishment Complete' THEN 1 ELSE 0 END) as TotalCanisters
from mck_hvs.replevent t
where
CAST(t.time as DATE) = CAST(GETDATE() as DATE)
and t.stationtype IN ('T', 'S')
and t.eventtype = 'Replenishment Complete'
group by
t.operator,
t.eventtype
Second query:
select
UPPER(o.operator) as Operator,
SUM(CASE WHEN o.eventtype = 'GoodScan' THEN 1 ELSE 0 END) as TotalScans,
convert( varchar(19), MIN(o.time), 8) as LogonTime,
DATEDIFF(MINUTE, MIN(o.time), MAX(o.time)) as TotalMinLogon
from mck_hvs.replevent o
where
CAST(o.time as DATE) = CAST(GETDATE() as DATE)
and o.eventtype IN ( 'Replenishment Complete', 'GoodScan' )
group by
o.operator
order by o.operator
Something like the below should get you headed to a solution. I removed the group on t.eventtype and removed from the case statements because the where clause already limited the results for you.
select
op.Operator,
op.TotalScans,
op.LogonTime,
op.TotalMinLogon,
b.[6AM],
b.[7AM],
b.[8AM],
b.[9AM],
b.[10AM],
b.[11AM],
b.[12PM],
b.[1PM],
b.[2PM],
b.[3PM],
b.[4PM],
b.[5PM],
b.[6+PM]
from
(
select
UPPER(o.operator) as Operator,
SUM(CASE WHEN o.eventtype = 'GoodScan' THEN 1 ELSE 0 END) as TotalScans,
convert( varchar(19), MIN(o.time), 8) as LogonTime,
DATEDIFF(MINUTE, MIN(o.time), MAX(o.time)) as TotalMinLogon
from mck_hvs.replevent o
where
--will use o.time index now:
o.time >= CAST(GETDATE() as DATE)
and o.time < CAST(dateadd(Day,1,GETDATE()) as DATE)
and o.eventtype IN ( 'Replenishment Complete', 'GoodScan' )
group by
o.operator
) as op
left join
(
select
UPPER(t.operator) as Operator,
SUM(CASE WHEN DATEPART(HOUR,t.time) = 6 THEN 1 ELSE 0 END) AS '6AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 7 THEN 1 ELSE 0 END) AS '7AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 8 THEN 1 ELSE 0 END) AS '8AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 9 THEN 1 ELSE 0 END) AS '9AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 10 THEN 1 ELSE 0 END) AS '10AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 11 THEN 1 ELSE 0 END) AS '11AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 12 THEN 1 ELSE 0 END) AS '12PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 13 THEN 1 ELSE 0 END) AS '1PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 14 THEN 1 ELSE 0 END) AS '2PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 15 THEN 1 ELSE 0 END) AS '3PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 16 THEN 1 ELSE 0 END) AS '4PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 17 THEN 1 ELSE 0 END) AS '5PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) > 17 THEN 1 ELSE 0 END) AS '6+PM',
SUM(CASE WHEN t.eventtype = 'Replenishment Complete' THEN 1 ELSE 0 END) as TotalCanisters
from mck_hvs.replevent t
where
--will use o.time index now:
o.time >= CAST(GETDATE() as DATE)
and o.time < CAST(dateadd(Day,1,GETDATE()) as DATE)
and t.stationtype IN ('T', 'S')
and t.eventtype = 'Replenishment Complete'
group by
t.operator
) as b
on b.Operator = op.Operator
SELECT l.* ,
r.TotalScans ,
r.LogonTime ,
r.TotalMinLogon
FROM ( SELECT UPPER(t.operator) AS Operator ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 6
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '6AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 7
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '7AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 8
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '8AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 9
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '9AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 10
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '10AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 11
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '11AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 12
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '12PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 13
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '1PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 14
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '2PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 15
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '3PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 16
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '4PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 17
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '5PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( COUNT(CASE WHEN DATEPART(HOUR, t.time) > 17
THEN t.eventtype
ELSE NULL
END) )
ELSE NULL
END AS '6+PM' ,
SUM(CASE WHEN t.eventtype = 'Replenishment Complete'
THEN 1
ELSE 0
END) AS TotalCanisters
FROM #replevent t
WHERE CAST(t.time AS DATE) = CAST(GETDATE() AS DATE)
AND t.stationtype IN ( 'T', 'S' )
AND t.eventtype = 'Replenishment Complete'
GROUP BY t.operator ,
t.eventtype
) AS l
INNER JOIN ( SELECT UPPER(o.operator) AS Operator_r ,
SUM(CASE WHEN o.eventtype = 'GoodScan' THEN 1
ELSE 0
END) AS TotalScans ,
CONVERT(VARCHAR(19), MIN(o.time), 8) AS LogonTime ,
DATEDIFF(SECOND, MIN(o.time), MAX(o.time)) AS TotalMinLogon
FROM #replevent o
WHERE CAST(o.time AS DATE) = CAST(GETDATE() AS DATE)
AND o.eventtype IN ( 'Replenishment Complete',
'GoodScan' )
GROUP BY o.operator
) AS r ON l.Operator = r.Operator_r
ORDER BY l.Operator;

SQL works in Query form but not View form. Error: Concat function requires 2 arguments

I imagine the answer to this query is related to here, however I am struggling.
Any help is much appreciated.
I am getting the following error message when running a piece of code.
The code works fine in Query form but not in view.
Code
SELECT
CASE
WHEN a.Sex = 1
THEN 'M'
WHEN a.Sex = 2
THEN 'F'
END AS Derived_Sex,
CASE
WHEN concat(b.Complete, a.[CALCULATED_AGE]) LIKE 'A%'
THEN 'Less than 1'
WHEN concat(b.Complete, a.[CALCULATED_AGE]) LIKE 'B%'
THEN 'Less than 1'
WHEN concat(b.Complete, a.[CALCULATED_AGE]) LIKE 'C%'
THEN 'Less than 1'
ELSE '1 year and above'
END AS Derived_InfantCat,
concat(left(b.Complete,2),a.[CALCULATED_AGE],substring(b.Complete,3,100)) AS [Calculated Age],
YEAR(a.DATE_OF_DEATH) AS [Derived_Year of Death],
FORMAT(a.DATE_OF_DEATH, 'MM') AS [Derived_Month of Death],
YEAR(a.DATE_OF_REGISTRATION) AS [Derived_Year of Registration],
FORMAT(a.DATE_OF_REGISTRATION, 'MM') AS [Derived_Month of Registration],
CONCAT(LEFT(CONVERT(nvarchar, a.DATE_OF_DEATH, 21), 4),
SUBSTRING(CONVERT(nvarchar, a.DATE_OF_DEATH, 21), 6, 2)) AS [Derived_YearMonth of Death],
CONCAT(LEFT(CONVERT(nvarchar, a.DATE_OF_REGISTRATION, 21), 4),
SUBSTRING(CONVERT(nvarchar, a.DATE_OF_REGISTRATION, 21), 6, 2)) AS [Derived_YearMonth of Registration],
CASE
WHEN LEN(
CASE
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) = ''
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) IS NULL
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE a.UNDERLYING_CAUSE_OF_DEATH
END) = 3
THEN CONCAT(
CASE
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) = ''
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) IS NULL
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE a.UNDERLYING_CAUSE_OF_DEATH
END, 'X')
ELSE
(CASE
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) = ''
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) IS NULL
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE a.UNDERLYING_CAUSE_OF_DEATH
END)
END AS [Derived_Cause of Death Code],
c.[4 character DESCRIPTION],
c.[3 character Sub-Chapter Description],
c.[Chapter Description],
d.[District_Name] AS [LA NAME],
e.[WD14NM] AS [WARD NAME],
a.[LSOA_OF_RESIDENCE_CODE] AS LSOA,
g.[Index of Multiple Deprivation (IMD) Score] AS [IMD 2015 Score],
g.[DERIVED_Havering Quintile (1 equals Most Deprived)] as [Havering Quintile],
(
CASE
WHEN a.[NHS_ESTABLISHMENT_IND] = '1'
THEN 'NHS'
WHEN a.[NHS_ESTABLISHMENT_IND] = '2'
THEN 'NON-NHS'
ELSE 'OTHER'
END) AS [NHS ESTABLISHMENT TYPE DESCRIPTION],
(
CASE
WHEN a.PLACE_OF_DEATH_CODE = 'H'
THEN 'HOME'
WHEN a.PLACE_OF_DEATH_CODE = 'E'
THEN 'ELSEWHERE'
ELSE 'OTHER'
END
) AS [PLACE OF DEATH CODE],
(
CASE
WHEN a.PLACE_OF_DEATH_CODE = 'H'
THEN ''
WHEN a.PLACE_OF_DEATH_CODE = 'E'
THEN ''
ELSE concat(a.[NHS_ESTABLISHMENT_IND],'-',a.PLACE_OF_DEATH_ESTAB_TYPE)
END
) AS [NHS ESTABLISHMENT CODE],
isnull(f.[Place of Death Establishment Type],a.PLACE_OF_DEATH_CODE) AS [PLACE OF DEATH ESTABLISHMENT TYPE]
FROM RAW.dbo.ONS_Death AS a
inner join REFERENCE.dbo.[ONS-PCMD_AGE] AS b
ON a.CALCULATED_AGE_UNIT = b.[Age Unit]
left outer JOIN REFERENCE.dbo.[OTH_ICD-10] AS c
ON
CASE
WHEN LEN(
CASE
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) = ''
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) IS NULL
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE a.UNDERLYING_CAUSE_OF_DEATH
END) = 3
THEN CONCAT
(
CASE
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) = ''
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) IS NULL
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE a.UNDERLYING_CAUSE_OF_DEATH
END, 'X')
ELSE (
CASE
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) = ''
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) IS NULL
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE a.UNDERLYING_CAUSE_OF_DEATH
END)
END = c.[4 CharacterDiagnosis Code]
LEFT OUTER JOIN REFERENCE.dbo.GEOG_LANames_1991 AS d
ON a.[ULA_OF_RESIDENCE_CODE] = d.[ONS_District_Code]
LEFT OUTER JOIN REFERENCE.dbo.GEOG_WardNames_2014 AS e ON { fn CONCAT(ISNULL(a.ULA_OF_RESIDENCE_CODE, ''), ISNULL(a.WARD_OF_RESIDENCE_CODE, '')) } = e.WD14CDO
LEFT OUTER JOIN REFERENCE.[dbo].[GEOG_NHSCE_EstabTypes_2016] AS f
ON
CASE
WHEN a.PLACE_OF_DEATH_CODE = 'H'
THEN ''
WHEN a.PLACE_OF_DEATH_CODE = 'E'
THEN ''
ELSE {fn concat({ fn CONCAT(ISNUll(convert(nvarchar,a.[NHS_ESTABLISHMENT_IND],21),''),'-')},isnull(convert(nvarchar,a.PLACE_OF_DEATH_ESTAB_TYPE,21),''))}
END = f.[Code]
LEFT OUTER JOIN REFERENCE.[dbo].[OTH_IMD2015] AS g
ON a.[LSOA_OF_RESIDENCE_CODE] = g.[LSOA code (2011)]
order by [Calculated Age]
The code above seems to prefix concatenate function with an {fn as shown below, if that helps anyone to solve this
SELECT
CASE WHEN aPCMD.Sex = 1 THEN 'M'
WHEN aPCMD.Sex = 2 THEN 'F'
ELSE 'unknown'
END AS Derived_Sex,
CASE WHEN concat(bAgeLookup.Complete, aPCMD.[CALCULATED_AGE]) LIKE 'A%' THEN 'Less than 1'
WHEN concat(bAgeLookup.Complete, aPCMD.[CALCULATED_AGE]) LIKE 'B%' THEN 'Less than 1'
WHEN concat(bAgeLookup.Complete, aPCMD.[CALCULATED_AGE]) LIKE 'C%' THEN 'Less than 1'
ELSE '1 year and above'
END AS Derived_InfantCat,
{ fn CONCAT(LEFT(bAgeLookup.Complete, 2), aPCMD.CALCULATED_AGE, SUBSTRING(bAgeLookup.Complete, 3, 100)) } AS Derived_Age,
YEAR(aPCMD.DATE_OF_DEATH) AS [Derived_Year of Death],
FORMAT(aPCMD.DATE_OF_DEATH, 'MM') AS [Derived_Month of Death],
YEAR(aPCMD.DATE_OF_REGISTRATION) AS [Derived_Year of Registration],
FORMAT(aPCMD.DATE_OF_REGISTRATION, 'MM') AS [Derived_Month of Registration],
{ fn CONCAT(LEFT(CONVERT(nvarchar, aPCMD.DATE_OF_DEATH, 21), 4), SUBSTRING(CONVERT(nvarchar, aPCMD.DATE_OF_DEATH, 21), 6, 2)) } AS [Derived_YearMonth of Death],
{ fn CONCAT(LEFT(CONVERT(nvarchar, aPCMD.DATE_OF_REGISTRATION, 21), 4), SUBSTRING(CONVERT(nvarchar, aPCMD.DATE_OF_REGISTRATION, 21), 6, 2)) } AS [Derived_YearMonth of Registration],
CASE WHEN LEN(
CASE WHEN (aPCMD.UNDERLYING_CAUSE_OF_DEATH) = '' THEN aPCMD.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (aPCMD.UNDERLYING_CAUSE_OF_DEATH) IS NULL THEN aPCMD.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE aPCMD.UNDERLYING_CAUSE_OF_DEATH
END) = 3
THEN CONCAT(CASE WHEN (aPCMD.UNDERLYING_CAUSE_OF_DEATH) = '' THEN aPCMD.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (aPCMD.UNDERLYING_CAUSE_OF_DEATH) IS NULL THEN aPCMD.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE aPCMD.UNDERLYING_CAUSE_OF_DEATH
END, 'X')
ELSE (CASE WHEN (aPCMD.UNDERLYING_CAUSE_OF_DEATH) = ''
THEN aPCMD.[CAUSE_OF_DEATH_ICD_CODE_1] WHEN (aPCMD.UNDERLYING_CAUSE_OF_DEATH) IS NULL
THEN aPCMD.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE aPCMD.UNDERLYING_CAUSE_OF_DEATH
END)
END AS [Derived_Cause of Death Code], cICD10.[4 character DESCRIPTION] AS Derived,
cICD10.[3 character Sub-Chapter Description],
cICD10.[Chapter Description],
d.District_Name AS [LA NAME],
e.WD14NM AS [WARD NAME],
aPCMD.LSOA_OF_RESIDENCE_CODE AS LSOA,
g.[Index of Multiple Deprivation (IMD) Score] AS [IMD 2015 Score],
g.[DERIVED_Havering Quintile (1 equals Most Deprived)] AS [Havering Quintile],
(CASE WHEN aPCMD.[NHS_ESTABLISHMENT_IND] = '1' THEN 'NHS'
WHEN aPCMD.[NHS_ESTABLISHMENT_IND] = '2' THEN 'NON-NHS'
ELSE 'OTHER'
END) AS [NHS ESTABLISHMENT TYPE DESCRIPTION],
(CASE WHEN aPCMD.PLACE_OF_DEATH_CODE = 'H' THEN 'HOME'
WHEN aPCMD.PLACE_OF_DEATH_CODE = 'E'
THEN 'ELSEWHERE'
ELSE 'OTHER' END) AS [PLACE OF DEATH CODE],
(CASE WHEN aPCMD.PLACE_OF_DEATH_CODE = 'H' THEN ''
WHEN aPCMD.PLACE_OF_DEATH_CODE = 'E' THEN ''
ELSE concat(aPCMD.[NHS_ESTABLISHMENT_IND], '-', aPCMD.PLACE_OF_DEATH_ESTAB_TYPE)
END) AS [NHS ESTABLISHMENT CODE],
ISNULL(f.[Place of Death Establishment Type],
aPCMD.PLACE_OF_DEATH_CODE) AS [PLACE OF DEATH ESTABLISHMENT TYPE]
 
FROM RAW.dbo.ONS_Death AS aPCMD
INNER JOIN REFERENCE.dbo.[ONS-PCMD_AGE] AS bAgeLookup
ON aPCMD.CALCULATED_AGE_UNIT = bAgeLookup.[Age Unit]
LEFT OUTER JOIN REFERENCE.dbo.[OTH_ICD-10] AS cICD10
ON CASE WHEN LEN(
CASE WHEN (aPCMD.UNDERLYING_CAUSE_OF_DEATH) = '' THEN aPCMD.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (aPCMD.UNDERLYING_CAUSE_OF_DEATH) IS NULL THEN aPCMD.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE aPCMD.UNDERLYING_CAUSE_OF_DEATH
END) = 3
THEN CONCAT( CASE WHEN (aPCMD.UNDERLYING_CAUSE_OF_DEATH) = '' THEN aPCMD.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (aPCMD.UNDERLYING_CAUSE_OF_DEATH) IS NULL THEN aPCMD.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE aPCMD.UNDERLYING_CAUSE_OF_DEATH
END, 'X')
ELSE (CASE WHEN (aPCMD.UNDERLYING_CAUSE_OF_DEATH) = '' THEN aPCMD.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (aPCMD.UNDERLYING_CAUSE_OF_DEATH) IS NULL THEN aPCMD.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE aPCMD.UNDERLYING_CAUSE_OF_DEATH
END)
END = cICD10.[4 CharacterDiagnosis Code]
LEFT OUTER JOIN REFERENCE.dbo.GEOG_LANames_1991 AS d
ON aPCMD.ULA_OF_RESIDENCE_CODE = d.ONS_District_Code
LEFT OUTER JOIN REFERENCE.dbo.GEOG_WardNames_2014 AS e
ON { fn CONCAT(ISNULL(aPCMD.ULA_OF_RESIDENCE_CODE, ''), ISNULL(aPCMD.WARD_OF_RESIDENCE_CODE, '')) } = e.WD14CDO
 
LEFT OUTER JOIN REFERENCE.dbo.GEOG_NHSCE_EstabTypes_2016 AS f
ON CASE WHEN aPCMD.PLACE_OF_DEATH_CODE = 'H' THEN ''
WHEN aPCMD.PLACE_OF_DEATH_CODE = 'E' THEN ''
ELSE { fn concat({ fn CONCAT(ISNUll(CONVERT(nvarchar, aPCMD.[NHS_ESTABLISHMENT_IND], 21), ''), '-') },
isnull(CONVERT(nvarchar, aPCMD.PLACE_OF_DEATH_ESTAB_TYPE, 21), '')) }
END = f.Code
LEFT OUTER JOIN REFERENCE.dbo.OTH_IMD2015 AS g ON aPCMD.LSOA_OF_RESIDENCE_CODE = g.[LSOA code (2011)]
Try with the below code..
SELECT
CASE
WHEN a.Sex = 1
THEN 'M'
WHEN a.Sex = 2
THEN 'F'
END AS Derived_Sex,
CASE
WHEN LTRIM(RTRIM(ISNULL(b.Complete,'')+ ISNULL(a.[CALCULATED_AGE],''))) LIKE 'A%'
THEN 'Less than 1'
WHEN LTRIM(RTRIM(ISNULL(b.Complete,'')+ ISNULL(a.[CALCULATED_AGE],''))) LIKE 'B%'
THEN 'Less than 1'
WHEN LTRIM(RTRIM(ISNULL(b.Complete,'')+ISNULL(a.[CALCULATED_AGE],''))) LIKE 'C%'
THEN 'Less than 1'
ELSE '1 year and above'
END AS Derived_InfantCat,
left(ISNULL(b.Complete,''),2)+ISNULL(a.[CALCULATED_AGE],'')+substring(ISNULL(b.Complete,''),3,100) AS [Calculated Age],
YEAR(a.DATE_OF_DEATH) AS [Derived_Year of Death],
FORMAT(a.DATE_OF_DEATH, 'MM') AS [Derived_Month of Death],
YEAR(a.DATE_OF_REGISTRATION) AS [Derived_Year of Registration],
FORMAT(a.DATE_OF_REGISTRATION, 'MM') AS [Derived_Month of Registration],
ISNULL(LEFT(CONVERT(nvarchar, a.DATE_OF_DEATH, 21), 4),'')+
ISNULL(SUBSTRING(CONVERT(nvarchar, a.DATE_OF_DEATH, 21), 6, 2),'') AS [Derived_YearMonth of Death],
ISNULL(LEFT(CONVERT(nvarchar, a.DATE_OF_REGISTRATION, 21), 4),'')+
ISNULL(SUBSTRING(CONVERT(nvarchar, a.DATE_OF_REGISTRATION, 21), 6, 2),'') AS [Derived_YearMonth of Registration],
CASE
WHEN LEN(
CASE
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) = ''
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) IS NULL
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE a.UNDERLYING_CAUSE_OF_DEATH
END) = 3
THEN CASE
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) = ''
THEN ISNULL(a.[CAUSE_OF_DEATH_ICD_CODE_1],'')
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) IS NULL
THEN ISNULL(a.[CAUSE_OF_DEATH_ICD_CODE_1],'')
ELSE ISNULL(a.UNDERLYING_CAUSE_OF_DEATH,'')
END+ 'X'
ELSE
(CASE
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) = ''
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) IS NULL
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE a.UNDERLYING_CAUSE_OF_DEATH
END)
END AS [Derived_Cause of Death Code],
c.[4 character DESCRIPTION],
c.[3 character Sub-Chapter Description],
c.[Chapter Description],
d.[District_Name] AS [LA NAME],
e.[WD14NM] AS [WARD NAME],
a.[LSOA_OF_RESIDENCE_CODE] AS LSOA,
g.[Index of Multiple Deprivation (IMD) Score] AS [IMD 2015 Score],
g.[DERIVED_Havering Quintile (1 equals Most Deprived)] as [Havering Quintile],
(
CASE
WHEN a.[NHS_ESTABLISHMENT_IND] = '1'
THEN 'NHS'
WHEN a.[NHS_ESTABLISHMENT_IND] = '2'
THEN 'NON-NHS'
ELSE 'OTHER'
END) AS [NHS ESTABLISHMENT TYPE DESCRIPTION],
(
CASE
WHEN a.PLACE_OF_DEATH_CODE = 'H'
THEN 'HOME'
WHEN a.PLACE_OF_DEATH_CODE = 'E'
THEN 'ELSEWHERE'
ELSE 'OTHER'
END
) AS [PLACE OF DEATH CODE],
(
CASE
WHEN a.PLACE_OF_DEATH_CODE = 'H'
THEN ''
WHEN a.PLACE_OF_DEATH_CODE = 'E'
THEN ''
ELSE ISNULL(a.[NHS_ESTABLISHMENT_IND],'')+'-'+ISNULL(a.PLACE_OF_DEATH_ESTAB_TYPE,'')
END
) AS [NHS ESTABLISHMENT CODE],
isnull(f.[Place of Death Establishment Type],a.PLACE_OF_DEATH_CODE) AS [PLACE OF DEATH ESTABLISHMENT TYPE]
FROM RAW.dbo.ONS_Death AS a
inner join REFERENCE.dbo.[ONS-PCMD_AGE] AS b
ON a.CALCULATED_AGE_UNIT = b.[Age Unit]
left outer JOIN REFERENCE.dbo.[OTH_ICD-10] AS c
ON
CASE
WHEN LEN(
CASE
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) = ''
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) IS NULL
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE a.UNDERLYING_CAUSE_OF_DEATH
END) = 3
THEN CASE
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) = ''
THEN ISNULL(a.[CAUSE_OF_DEATH_ICD_CODE_1],'')
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) IS NULL
THEN ISNULL(a.[CAUSE_OF_DEATH_ICD_CODE_1],'')
ELSE ISNULL(a.UNDERLYING_CAUSE_OF_DEATH,'')
END+ 'X'
ELSE (
CASE
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) = ''
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
WHEN (a.UNDERLYING_CAUSE_OF_DEATH) IS NULL
THEN a.[CAUSE_OF_DEATH_ICD_CODE_1]
ELSE a.UNDERLYING_CAUSE_OF_DEATH
END)
END = c.[4 CharacterDiagnosis Code]
LEFT OUTER JOIN REFERENCE.dbo.GEOG_LANames_1991 AS d
ON a.[ULA_OF_RESIDENCE_CODE] = d.[ONS_District_Code]
LEFT OUTER JOIN REFERENCE.dbo.GEOG_WardNames_2014 AS e ON ISNULL(a.ULA_OF_RESIDENCE_CODE, '')+ ISNULL(a.WARD_OF_RESIDENCE_CODE, '') = e.WD14CDO
LEFT OUTER JOIN REFERENCE.[dbo].[GEOG_NHSCE_EstabTypes_2016] AS f
ON
CASE
WHEN a.PLACE_OF_DEATH_CODE = 'H'
THEN ''
WHEN a.PLACE_OF_DEATH_CODE = 'E'
THEN ''
ELSE ISNUll(convert(nvarchar,a.[NHS_ESTABLISHMENT_IND],21),'')+'-'+isnull(convert(nvarchar,a.PLACE_OF_DEATH_ESTAB_TYPE,21),'')
END = f.[Code]
LEFT OUTER JOIN REFERENCE.[dbo].[OTH_IMD2015] AS g
ON a.[LSOA_OF_RESIDENCE_CODE] = g.[LSOA code (2011)]
ORDER BY [Calculated Age]

Join a Query with another Query while using a common table expression

I have the following 2 queries:
Query 1:
WITH JobTransactionsSumTypes AS
(
SELECT
[Job],
[Cost_Code],
SUM(CASE WHEN [Transaction_Type] = 'AP cost' AND [Commitment] <>'' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS APcostAmountComSum,
SUM(CASE WHEN [Transaction_Type] = 'AP cost' AND [Commitment] ='' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS APcostAmountNonComSum,
SUM(CASE WHEN [Transaction_Type] = 'Approved est changes' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS ApprovedEstChangesAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Aprvd cmmtt cst chng' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS AprvdCmmttCstChngAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Aprvd schdl val chn' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS AprvdSchdlValChnAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Cash receipt' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS CashReceiptAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Committed cost' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS CommittedCostAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Dollars paid' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS DollarsPaidAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'General Ledger only' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS GeneralLedgerOnlyAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'JC cost' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS JCcostAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 1' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet1AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 2' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet2AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 3' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet3AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 4' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet4AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Original estimate' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS OriginalEstimateAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pending est changes' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PendingEstChangesAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Percent complete' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PercentCompleteAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng cmmtt cst chng' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngCmmttCstChngAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng schd val chg 2' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngSchdValChg2AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng schd val chg 3' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngSchdValChg3AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng schdl val chng' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngSchdlValChngAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'PR cost' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PRcostAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Receivable Adjstment' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS ReceivableAdjstmentAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Retention billed' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS RetentionBilledAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Scheduled value' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS ScheduledValueAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Work Billed' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS WorkBilledAmountSum
FROM [ADCData_Doric].[dbo].[JCT_CURRENT__TRANSACTION]
WHERE
GROUP BY
[Job],
[Cost_Code]
)
SELECT
Job,
Cost_Code,
APcostAmountComSum,
APcostAmountNonComSum,
ApprovedEstChangesAmountSum,
AprvdCmmttCstChngAmountSum,
AprvdSchdlValChnAmountSum,
CashReceiptAmountSum,
CommittedCostAmountSum,
DollarsPaidAmountSum,
GeneralLedgerOnlyAmountSum,
JCcostAmountSum,
MiscWorksheet1AmountSum,
MiscWorksheet2AmountSum,
MiscWorksheet3AmountSum,
MiscWorksheet4AmountSum,
OriginalEstimateAmountSum,
PendingEstChangesAmountSum,
PercentCompleteAmountSum,
PndngCmmttCstChngAmountSum,
PndngSchdValChg2AmountSum,
PndngSchdValChg3AmountSum,
PndngSchdlValChngAmountSum,
PRcostAmountSum,
ReceivableAdjstmentAmountSum,
RetentionBilledAmountSum,
ScheduledValueAmountSum,
WorkBilledAmountSum,
(ScheduledValueAmountSum) AS StartContractAmount,
(AprvdSchdlValChnAmountSum) AS ApprovedVariations,
(OriginalEstimateAmountSum + ApprovedEstChangesAmountSum + PendingEstChangesAmountSum) AS TotalBudgetOriginalApprovedPending,
(OriginalEstimateAmountSum + ApprovedEstChangesAmountSum)*(MiscWorksheet1AmountSum/100)+(PendingEstChangesAmountSum*(MiscWorksheet2AmountSum/100)) AS TotalCommitmentsBudget,
(CommittedCostAmountSum + AprvdCmmttCstChngAmountSum + PndngCmmttCstChngAmountSum) AS ApprovedPendingCommitedCosts
-- You Could Add additional Calculations here.
FROM
[JobTransactionsSumTypes]
Query 2:
SELECT
APM_MASTER__DISTRIBUTION.Job
, APM_MASTER__DISTRIBUTION.Cost_Code
,SUM(CASE WHEN APM_MASTER__DISTRIBUTION.Onhold_Status <>0 THEN JCT_CURRENT__TRANSACTION.Amount-JCT_CURRENT__TRANSACTION.Noncosted_Tax ELSE 0 END) AS OnHoldAmount
,SUM(CASE WHEN APM_MASTER__DISTRIBUTION.Onhold_Status =0 THEN JCT_CURRENT__TRANSACTION.Amount-JCT_CURRENT__TRANSACTION.Noncosted_Tax ELSE 0 END) AS NotOnHoldAmount
FROM
dbo.JCT_CURRENT__TRANSACTION JCT_CURRENT__TRANSACTION
LEFT OUTER JOIN dbo.APM_MASTER__DISTRIBUTION APM_MASTER__DISTRIBUTION
ON JCT_CURRENT__TRANSACTION.Vendor = APM_MASTER__DISTRIBUTION.Vendor AND JCT_CURRENT__TRANSACTION.Invoice = APM_MASTER__DISTRIBUTION.Invoice AND JCT_CURRENT__TRANSACTION.Dist_Sequence = APM_MASTER__DISTRIBUTION.Dist_Seq
GROUP BY
APM_MASTER__DISTRIBUTION.Job
, APM_MASTER__DISTRIBUTION.Cost_Code
I can join these in Crystal reports, but would like to move this into a single query through left outer joining (getting all Query 1 Results) and linking through the job and cost code to query 2.
I suppose what I am asking is, Query 1 uses a common table expression but query 2 does not, and i'm not sure how to join them.
Thanks.
You can use multiple CTE in one query
Simple example:
;WITH cte1 AS
(
SELECT *
FROM table1
), AS cte2
(
SELECT *
FROM table2
)
SELECT *
FROM cte1 c1 LEFT JOIN cte2 c2 ON c1.id = c2.id
Your query with multiple CTE
;WITH JobTransactionsSumTypes AS
(
SELECT
[Job],
[Cost_Code],
SUM(CASE WHEN [Transaction_Type] = 'AP cost' AND [Commitment] <>'' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS APcostAmountComSum,
SUM(CASE WHEN [Transaction_Type] = 'AP cost' AND [Commitment] ='' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS APcostAmountNonComSum,
SUM(CASE WHEN [Transaction_Type] = 'Approved est changes' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS ApprovedEstChangesAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Aprvd cmmtt cst chng' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS AprvdCmmttCstChngAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Aprvd schdl val chn' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS AprvdSchdlValChnAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Cash receipt' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS CashReceiptAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Committed cost' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS CommittedCostAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Dollars paid' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS DollarsPaidAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'General Ledger only' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS GeneralLedgerOnlyAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'JC cost' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS JCcostAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 1' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet1AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 2' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet2AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 3' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet3AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 4' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet4AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Original estimate' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS OriginalEstimateAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pending est changes' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PendingEstChangesAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Percent complete' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PercentCompleteAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng cmmtt cst chng' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngCmmttCstChngAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng schd val chg 2' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngSchdValChg2AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng schd val chg 3' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngSchdValChg3AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng schdl val chng' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngSchdlValChngAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'PR cost' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PRcostAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Receivable Adjstment' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS ReceivableAdjstmentAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Retention billed' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS RetentionBilledAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Scheduled value' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS ScheduledValueAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Work Billed' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS WorkBilledAmountSum
FROM [ADCData_Doric].[dbo].[JCT_CURRENT__TRANSACTION]
--WHERE your_condition
GROUP BY
[Job],
[Cost_Code]
), JobTransactionsSumTypes_Query2 AS
(
SELECT
APM_MASTER__DISTRIBUTION.Job
, APM_MASTER__DISTRIBUTION.Cost_Code
,SUM(CASE WHEN APM_MASTER__DISTRIBUTION.Onhold_Status <>0 THEN JCT_CURRENT__TRANSACTION.Amount-JCT_CURRENT__TRANSACTION.Noncosted_Tax ELSE 0 END) AS OnHoldAmount
,SUM(CASE WHEN APM_MASTER__DISTRIBUTION.Onhold_Status =0 THEN JCT_CURRENT__TRANSACTION.Amount-JCT_CURRENT__TRANSACTION.Noncosted_Tax ELSE 0 END) AS NotOnHoldAmount
FROM
dbo.JCT_CURRENT__TRANSACTION JCT_CURRENT__TRANSACTION
LEFT OUTER JOIN dbo.APM_MASTER__DISTRIBUTION APM_MASTER__DISTRIBUTION
ON JCT_CURRENT__TRANSACTION.Vendor = APM_MASTER__DISTRIBUTION.Vendor AND JCT_CURRENT__TRANSACTION.Invoice = APM_MASTER__DISTRIBUTION.Invoice AND JCT_CURRENT__TRANSACTION.Dist_Sequence = APM_MASTER__DISTRIBUTION.Dist_Seq
GROUP BY
APM_MASTER__DISTRIBUTION.Job
,APM_MASTER__DISTRIBUTION.Cost_Code
)
SELECT
Job,
Cost_Code,
APcostAmountComSum,
APcostAmountNonComSum,
ApprovedEstChangesAmountSum,
AprvdCmmttCstChngAmountSum,
AprvdSchdlValChnAmountSum,
CashReceiptAmountSum,
CommittedCostAmountSum,
DollarsPaidAmountSum,
GeneralLedgerOnlyAmountSum,
JCcostAmountSum,
MiscWorksheet1AmountSum,
MiscWorksheet2AmountSum,
MiscWorksheet3AmountSum,
MiscWorksheet4AmountSum,
OriginalEstimateAmountSum,
PendingEstChangesAmountSum,
PercentCompleteAmountSum,
PndngCmmttCstChngAmountSum,
PndngSchdValChg2AmountSum,
PndngSchdValChg3AmountSum,
PndngSchdlValChngAmountSum,
PRcostAmountSum,
ReceivableAdjstmentAmountSum,
RetentionBilledAmountSum,
ScheduledValueAmountSum,
WorkBilledAmountSum,
(ScheduledValueAmountSum) AS StartContractAmount,
(AprvdSchdlValChnAmountSum) AS ApprovedVariations,
(OriginalEstimateAmountSum + ApprovedEstChangesAmountSum + PendingEstChangesAmountSum) AS TotalBudgetOriginalApprovedPending,
(OriginalEstimateAmountSum + ApprovedEstChangesAmountSum)*(MiscWorksheet1AmountSum/100)+(PendingEstChangesAmountSum*(MiscWorksheet2AmountSum/100)) AS TotalCommitmentsBudget,
(CommittedCostAmountSum + AprvdCmmttCstChngAmountSum + PndngCmmttCstChngAmountSum) AS ApprovedPendingCommitedCosts,
j2.OnHoldAmount,
j2.NotOnHoldAmount
FROM
[JobTransactionsSumTypes] j1 LEFT OUTER JOIN JobTransactionsSumTypes_Query2 j2
ON j1.Job = j2.Job AND j1.Cost_Code = j2.Cost_Code