Is a combined subquery possible for this scenario? - sql

I currently have this over long query that I'm trying to optimize. I looked at combining subquery's but I fail to get a count for every group in one query while having my constraints.
Is it possible to slim down the following query?
SELECT
val_year,
spg,
SUM(val_q1) val_q1,
SUM(val_q2) val_q2,
SUM(val_q3) val_q3,
SUM(val_q4) val_q4,
SUM(val_q1) + SUM(val_q2) + SUM(val_q3) + SUM(val_q4) val_total
FROM (
SELECT
val_year,
spg,
count_prods val_q1,
0 val_q2,
0 val_q3,
0 val_q4
FROM table_report
WHERE val_quarter = 'Q1'
UNION ALL
SELECT
val_year,
spg,
0 val_q1,
count_prods val_q2,
0 val_q3,
0 val_q4
FROM table_report
WHERE val_quarter = 'Q2'
UNION ALL
SELECT
val_year,
spg,
0 val_q1,
0 val_q2,
count_prods val_q3,
0 val_q4
FROM table_report
WHERE val_quarter = 'Q3'
UNION ALL
SELECT
val_year,
spg,
0 val_q1,
0 val_q2,
0 val_q3,
count_prods val_q4
FROM table_report
WHERE val_quarter = 'Q4'
)
table_report looks like this:
table_report:
val_year VARCHAR2(4)
spg VARCHAR2(256)
val_quarter VARCHAR2(2)
count_prods NUMBER(10)

You can replace the UNIONs with a single query using CASEs:
SELECT
val_year,
spg,
CASE WHEN val_quarter = 'Q1' THEN count_prods ELSE 0 END val_q1,
CASE WHEN val_quarter = 'Q2' THEN count_prods ELSE 0 END val_q2,
CASE WHEN val_quarter = 'Q3' THEN count_prods ELSE 0 END val_q3,
CASE WHEN val_quarter = 'Q4' THEN count_prods ELSE 0 END val_q4
FROM table_report

It looks like a PIVOT query, so you could do all in one
SELECT
val_year, spg,
coalesce(q1_total, 0) as q1,
coalesce(q2_total, 0) as q2,
coalesce(q3_total, 0) as q3,
coalesce(q4_total, 0) as q4,
coalesce(q1_total, 0) + coalesce(q2_total, 0) + coalesce(q3_total, 0) + coalesce(q4_total, 0) as total
FROM
(SELECT val_Year, spg, count_prod, val_quarter FROM test)
PIVOT (SUM(count_prod) as total
FOR (val_Quarter) IN ('Q1' AS q1, 'Q2' AS q2, 'Q3' AS q3, 'Q4' as q4))s ;
see SqlFiddle

As per my understanding, you can directly use group by query to get the sum count of each quarter -
like
select sum(count_prods) mysum, val_quarter as quarter group by quarter;

I'm not sure exactly what result you are trying to obtain, but perhaps you can try an approach like this:
SELECT
val_year,
spg,
val_q1,
val_q2,
val_q3,
val_q4,
val_q1 + val_q2 + val_q3 + val_q4 as val_total
FROM (
SELECT
val_year,
spg,
sum(case when val_quarter = 'Q1' then count_prods else 0 end) as val_q1,
sum(case when val_quarter = 'Q2' then count_prods else 0 end) as val_q2,
sum(case when val_quarter = 'Q3' then count_prods else 0 end) as val_q3,
sum(case when val_quarter = 'Q4' then count_prods else 0 end) as val_q4
FROM table_report
GROUP BY val_year, spg
)
Here it is in a no-data fiddle : http://sqlfiddle.com/#!4/9bf262/20

Related

sql grouping into one column

I wrote following sql query for a report.
Select AT.OTHER_GL_CODE As ACC,
GL.GL_ID,
GL.GL_NAME,
(Case When (
AT.OTHER_TRN_DEC = 'Cash'
And AT.OTHER_CR_DR = 'CR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'CASHCR',
(Case When (
AT.OTHER_TRN_DEC = 'Cash'
And AT.OTHER_CR_DR = 'DR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'CASHDR',
(Case When (
AT.OTHER_TRN_DEC <> 'Cash'
And AT.OTHER_CR_DR = 'CR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'OTHERCR',
(Case When (
AT.OTHER_TRN_DEC <> 'Cash'
And AT.OTHER_CR_DR = 'DR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'OTHERDR',
AT.OTHER_BRN_CODE BRNCODE,
(
Select Sum( Case When TR.CR_DR = 'DR'
And TR.BRANCH_CODE = 1000
And TR.TRAN_DATE < '2017-07-01' Then TR.GL_TRN_AMT
Else 0
End
)
From COREBANKER1.dbo.GL_DAILY_TRN As TR
Where TR.GL_CODE = AT.OTHER_GL_CODE
) As DRBRFORE,
(
Select Sum( Case When TR.CR_DR = 'CR'
And TR.BRANCH_CODE = 1000
And TR.TRAN_DATE < '2017-07-01' Then TR.GL_TRN_AMT
Else 0
End
)
From COREBANKER1.dbo.GL_DAILY_TRN As TR
Where TR.GL_CODE = AT.OTHER_GL_CODE
) As CRBRFORE
From COREBANKER1.dbo.MAIN_OTHER_TRN As AT,
COREBANKER1.dbo.GL_MAIN As GL
Where AT.OTHER_BRN_CODE = 1000
And GL.GL_ID = AT.OTHER_GL_CODE
And AT.OTHER_BANK_DATE
Between '2017-07-01' And '2017-07-30';
this is the output
but my desired output is here
So how I change my query for desired result(grouping to ACC and GL_ID)?
The quick and dirty approach is to wrap the entire query and group by, this would prevent duplicate values in your 3,4,5, 6th columns.
The cleaner approach would be to take those 4 columns and wrap each one in a Select SUM(...) as you did for the later columns.
In short, no GROUP BY will leave you with duplicates - I took the liberty of giving you the syntax for the quick and dirty approach, see below.
SELECT
ACC
,GL_ID
,GL_NAME
,SUM(CASHCR) AS CASHCR
,SUM(CASHDR) AS CASHDR
,SUM(OTHERCR) AS OTHERCR
,SUM(OTHERDR) AS OTHERDR
,BRNCODE
,DRBRFORE
,CRBRFORE
FROM (
Select AT.OTHER_GL_CODE As ACC,
GL.GL_ID,
GL.GL_NAME,
(Case When (
AT.OTHER_TRN_DEC = 'Cash'
And AT.OTHER_CR_DR = 'CR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'CASHCR',
(Case When (
AT.OTHER_TRN_DEC = 'Cash'
And AT.OTHER_CR_DR = 'DR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'CASHDR',
(Case When (
AT.OTHER_TRN_DEC <> 'Cash'
And AT.OTHER_CR_DR = 'CR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'OTHERCR',
(Case When (
AT.OTHER_TRN_DEC <> 'Cash'
And AT.OTHER_CR_DR = 'DR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'OTHERDR',
AT.OTHER_BRN_CODE BRNCODE,
(
Select Sum( Case When TR.CR_DR = 'DR'
And TR.BRANCH_CODE = 1000
And TR.TRAN_DATE < '2017-07-01' Then TR.GL_TRN_AMT
Else 0
End
)
From COREBANKER1.dbo.GL_DAILY_TRN As TR
Where TR.GL_CODE = AT.OTHER_GL_CODE
) As DRBRFORE,
(
Select Sum( Case When TR.CR_DR = 'CR'
And TR.BRANCH_CODE = 1000
And TR.TRAN_DATE < '2017-07-01' Then TR.GL_TRN_AMT
Else 0
End
)
From COREBANKER1.dbo.GL_DAILY_TRN As TR
Where TR.GL_CODE = AT.OTHER_GL_CODE
) As CRBRFORE
From COREBANKER1.dbo.MAIN_OTHER_TRN As AT,
COREBANKER1.dbo.GL_MAIN As GL
Where AT.OTHER_BRN_CODE = 1000
And GL.GL_ID = AT.OTHER_GL_CODE
And AT.OTHER_BANK_DATE
Between '2017-07-01' And '2017-07-30'
)A
GROUP BY
ACC
,GL_ID
,GL_NAME
,CASHCR
,CASHDR
,OTHERCR
,OTHERDR
,BRNCODE
,DRBRFORE
,CRBRFORE
;
You could surround your query with a CTE then aggregate the fields you require.
WITH this as
(
Select AT.OTHER_GL_CODE As ACC,
GL.GL_ID,
GL.GL_NAME,
(Case When (
AT.OTHER_TRN_DEC = 'Cash'
And AT.OTHER_CR_DR = 'CR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'CASHCR',
(Case When (
AT.OTHER_TRN_DEC = 'Cash'
And AT.OTHER_CR_DR = 'DR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'CASHDR',
(Case When (
AT.OTHER_TRN_DEC <> 'Cash'
And AT.OTHER_CR_DR = 'CR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'OTHERCR',
(Case When (
AT.OTHER_TRN_DEC <> 'Cash'
And AT.OTHER_CR_DR = 'DR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'OTHERDR',
AT.OTHER_BRN_CODE BRNCODE,
(
Select Sum( Case When TR.CR_DR = 'DR'
And TR.BRANCH_CODE = 1000
And TR.TRAN_DATE < '2017-07-01' Then TR.GL_TRN_AMT
Else 0
End
)
From COREBANKER1.dbo.GL_DAILY_TRN As TR
Where TR.GL_CODE = AT.OTHER_GL_CODE
) As DRBRFORE,
(
Select Sum( Case When TR.CR_DR = 'CR'
And TR.BRANCH_CODE = 1000
And TR.TRAN_DATE < '2017-07-01' Then TR.GL_TRN_AMT
Else 0
End
)
From COREBANKER1.dbo.GL_DAILY_TRN As TR
Where TR.GL_CODE = AT.OTHER_GL_CODE
) As CRBRFORE
From COREBANKER1.dbo.MAIN_OTHER_TRN As AT,
COREBANKER1.dbo.GL_MAIN As GL
Where AT.OTHER_BRN_CODE = 1000
And GL.GL_ID = AT.OTHER_GL_CODE
And AT.OTHER_BANK_DATE
Between '2017-07-01' And '2017-07-30';
)
)
SELECT ACC ,GL_ID ,GL_NAME, SUM(CASHCR) AS CASHCR ,SUM(CASHDR) AS CASHDR ,SUM(OTHERCR) AS OTHERCR ,SUM(OTHERDR) AS OTHERDR, BRNCODE, DRBRFORE, CRBRFORE
FROM this
GROUP BY ACC ,GL_ID ,GL_NAME /*,CASHCR ,CASHDR ,OTHERCR ,OTHERDR */,BRNCODE
,DRBRFORE ,CRBRFORE

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;

I Need to get a count of activities by month grouped by a Department

I am trying to get a count of activities by month and group them by a department name. The report is based on a date parameter that I input to the query "#rptDate". What I have below works, but I'm guessing there is a better way of doing the same thing and hoping someone can shed some light.
Select Count(*) As Month1Count, 0 As Month2Count, 0 As Month3Count,
0 As Month4Count, 0 as Month5Count, 0 as Month6Count, 0 as Month7Count,
0 as Month8Count, 0 as Month9COunt, 0 as Month10Count, 0 as Month11Count,
0 as Month12Count, DepartmentName,ActivityDescription
from reports.WorkOrders
WHERE Month(BeginDate) = Month(#rptDate) and Year(BeginDate) = Year(#rptDate)
Group By DepartmentName, ActivityDescription
UNION
Select 0 As Month1Count, COUNT(*) As Month2Count, 0 as Month3Count,
0 as Month4Count, 0 as Month5Count, 0 as Month6Count, 0 as Month7Count,
0 as Month8Count, 0 as Month9COunt, 0 as Month10Count, 0 as Month11Count,
0 as Month12Count, DepartmentName,ActivityDescription
from reports.WorkOrders
WHERE Month(BeginDate) = Month(#rptDate) + 1 and Year(BeginDate) = Year(DateAdd(month,1,#rptDate))
Group By DepartmentName, ActivityDescription
UNION
Select 0 As Month1Count, 0 As Month2Count, Count(*) as Month3Count,
0 as Month4Count, 0 as Month5Count, 0 as Month6Count, 0 as Month7Count,
0 as Month8Count, 0 as Month9COunt, 0 as Month10Count, 0 as Month11Count,
0 as Month12Count, DepartmentName, ActivityDescription
from reports.WorkOrders
WHERE Month(BeginDate) = Month(#rptDate) + 2 and Year(BeginDate) = Year(DateAdd(month,2,#rptDate))
Group By DepartmentName, ActivityDescription
I haven't tested the following, so it's possible there are some typos or minor errors, but I think the following is what you want:
SELECT
sum(case when Month(BeginDate) = Month(dateadd(month, 0, #rptDate)) then 1 else 0 end) as Month1Count,
sum(case when Month(BeginDate) = Month(dateadd(month, 1, #rptDate)) then 1 else 0 end) as Month2Count,
sum(case when Month(BeginDate) = Month(dateadd(month, 2, #rptDate)) then 1 else 0 end) as Month3Count,
sum(case when Month(BeginDate) = Month(dateadd(month, 3, #rptDate)) then 1 else 0 end) as Month4Count,
sum(case when Month(BeginDate) = Month(dateadd(month, 4, #rptDate)) then 1 else 0 end) as Month5Count,
sum(case when Month(BeginDate) = Month(dateadd(month, 5, #rptDate)) then 1 else 0 end) as Month6Count,
sum(case when Month(BeginDate) = Month(dateadd(month, 6, #rptDate)) then 1 else 0 end) as Month7Count,
sum(case when Month(BeginDate) = Month(dateadd(month, 7, #rptDate)) then 1 else 0 end) as Month8Count,
sum(case when Month(BeginDate) = Month(dateadd(month, 8, #rptDate)) then 1 else 0 end) as Month9Count,
sum(case when Month(BeginDate) = Month(dateadd(month, 9, #rptDate)) then 1 else 0 end) as Month10Count,
sum(case when Month(BeginDate) = Month(dateadd(month, 10, #rptDate)) then 1 else 0 end) as Month11Count,
sum(case when Month(BeginDate) = Month(dateadd(month, 11, #rptDate)) then 1 else 0 end) as Month12Count
DepartmentName,
ActivityDescription
FROM
reports.WorkOrders
WHERE
Year(BeginDate) + right('0'+Month(BeginDate),2)
between Year(#rptDate) + right('0'+Month(#rptDate),2)
and Year(dateadd(month,11,#rptDate)) + right('0'+Month(dateadd(month,11,#rptDate)),2)
GROUP BY
DepartmentName,
ActivityDescription
Do let me know how you get on with this. If I've made typos and you can't correct for them, do report the error message and/or any problems with the results.

Optimize this chain of Views

I've a set of 6 Viewsthat i use to gather the data i need for an excel report.
View 1
SELECT *, MONTH(DataEmissione) AS Mese_Emissione, YEAR(DataEmissione) AS Anno_Emissione, CASE WHEN StatoEmissione = 'R' THEN - ImpVetComp WHEN StatoBiglietto = 'VR' THEN ImpVetComp * 0 WHEN StatoEmissione = 'NC' THEN ImpVetComp * 0 WHEN StatoEmissione = 'AN' THEN ImpVetComp * 0 ELSE ImpVetComp END AS Fare, DATENAME(month, DataEmissione) AS Issue_Month_Name, DATEPART(quarter, DataEmissione) AS Quarter, YEAR(DATEADD(month, - 3, DataEmissione)) AS AnnoFiscale, CASE WHEN MONTH(DataEmissione) < 4 THEN MONTH(DataEmissione) + 9 ELSE MONTH(DataEmissione) - 3 END AS Fiscal_Month, REPLACE(REPLACE(Destinazione, ' ', ''), '-', '') AS Destinazione_Normalizzata
FROM Gabbiano.dbo.PRAB0000
WHERE (DataEmissione >= DATEADD(year, - 3, GETDATE()))
UNION ALL
SELECT *, MONTH(DataEmissione) AS Mese_Emissione, YEAR(DataEmissione) AS Anno_Emissione, CASE WHEN StatoEmissione = 'R' THEN - ImpVetComp WHEN StatoBiglietto = 'VR' THEN ImpVetComp * 0 WHEN StatoEmissione = 'NC' THEN ImpVetComp * 0 WHEN StatoEmissione = 'AN' THEN ImpVetComp * 0 ELSE ImpVetComp END AS Fare, DATENAME(month, DataEmissione) AS Issue_Month_Name, DATEPART(quarter, DataEmissione) AS Quarter, YEAR(DATEADD(month, - 3, DataEmissione)) AS AnnoFiscale, CASE WHEN MONTH(DataEmissione) < 4 THEN MONTH(DataEmissione) + 9 ELSE MONTH(DataEmissione) - 3 END AS Fiscal_Month, REPLACE(REPLACE(Destinazione, ' ', ''), '-', '') AS Destinazione_Normalizzata
FROM Istantravel.dbo.PRAB0000
WHERE (DataEmissione >= DATEADD(year, - 3, GETDATE()))
UNION ALL
SELECT *, MONTH(DataEmissione) AS Mese_Emissione, YEAR(DataEmissione) AS Anno_Emissione, CASE WHEN StatoEmissione = 'R' THEN - ImpVetComp WHEN StatoBiglietto = 'VR' THEN ImpVetComp * 0 WHEN StatoEmissione = 'NC' THEN ImpVetComp * 0 WHEN StatoEmissione = 'AN' THEN ImpVetComp * 0 ELSE ImpVetComp END AS Fare, DATENAME(month, DataEmissione) AS Issue_Month_Name, DATEPART(quarter, DataEmissione) AS Quarter, YEAR(DATEADD(month, - 3, DataEmissione)) AS AnnoFiscale, CASE WHEN MONTH(DataEmissione) < 4 THEN MONTH(DataEmissione) + 9 ELSE MONTH(DataEmissione) - 3 END AS Fiscal_Month, REPLACE(REPLACE(Destinazione, ' ', ''), '-', '') AS Destinazione_Normalizzata
FROM Globmaster.dbo.PRAB0000
WHERE (DataEmissione >= DATEADD(year, - 3, GETDATE()))
Views 2
SELECT biglietti.Agenzia, biglietti.CodiceCompagnia, biglietti.StatoBiglietto, biglietti.StatoEmissione, biglietti.CodicePersonale, biglietti.TipoTratta, biglietti.ClasseVettore, biglietti.MastroCliente, biglietti.SottocCliente,
biglietti.DataEmissione, biglietti.DataVariazione, biglietti.DataPartenza, biglietti.ImponibileVettore, biglietti.TasseAerop, biglietti.ImpCorrispettivi, biglietti.CorrispettiviAdd, biglietti.ScontoCommissioni,
biglietti.NumeroPax, biglietti.Destinazione, biglietti.ImpVetComp, biglietti.ImportoComm, biglietti.ImportoCommPass, biglietti.NumeroBiglietto, biglietti.NomePasseggero, biglietti.TasseYQ, biglietti.TasseYR,
biglietti.CodicePnr, biglietti.Mese_Emissione, biglietti.Anno_Emissione, biglietti.Fare, biglietti.Nome_Mese_Emissione, biglietti.Quarter, biglietti.Prop, biglietti.AnnoFiscale,
compagnie.Descrizione AS NomeCompagnia, compagnie.Categoria, compagnie.Alleanza,
CASE WHEN biglietti.Destinazione_Normalizzata = 'VOID' THEN 'VOID' WHEN biglietti.Destinazione_Normalizzata = 'CNJ' THEN 'CAMBI' WHEN biglietti.Destinazione_Normalizzata = 'conj' THEN 'CONGIUNZIONI'
WHEN datalength(biglietti.Destinazione_Normalizzata)
= 0 THEN 'NON INDICATA' WHEN biglietti.Destinazione_Normalizzata LIKE 'OR.ISSUE%' THEN 'RIEMISSIONI' ELSE SUBSTRING(biglietti.Destinazione_Normalizzata, 1, 3) END AS Partenza,
CASE WHEN biglietti.Destinazione_Normalizzata = 'VOID' THEN 'VOID' WHEN biglietti.Destinazione_Normalizzata = 'CNJ' THEN 'CAMBI' WHEN biglietti.Destinazione_Normalizzata = 'conj' THEN 'CONGIUNZIONI'
WHEN datalength(biglietti.Destinazione_Normalizzata)
= 0 THEN 'NON INDICATA' WHEN biglietti.Destinazione_Normalizzata LIKE 'OR.ISSUE%' THEN 'RIEMISSIONI' ELSE SUBSTRING(biglietti.Destinazione_Normalizzata, LEN(biglietti.Destinazione_Normalizzata)
/ 2 + 1 - 3, 3) END AS Arrivo,
CASE WHEN biglietti.Destinazione_Normalizzata = 'VOID' THEN 'VOID' WHEN biglietti.Destinazione_Normalizzata = 'CNJ' THEN 'CAMBI' WHEN biglietti.Destinazione_Normalizzata = 'conj' THEN 'CONGIUNZIONI'
WHEN datalength(biglietti.Destinazione_Normalizzata)
= 0 THEN 'NON INDICATA' WHEN biglietti.Destinazione_Normalizzata LIKE 'OR.ISSUE%' THEN 'RIEMISSIONI' ELSE SUBSTRING(biglietti.Destinazione_Normalizzata, LEN(biglietti.Destinazione_Normalizzata)
/ 2 + 1, 3) END AS DestinazioneFinale,
CASE WHEN biglietti.Destinazione_Normalizzata = 'VOID' THEN 'VOID' WHEN biglietti.Destinazione_Normalizzata = 'CNJ' THEN 'CAMBI' WHEN biglietti.Destinazione_Normalizzata = 'conj' THEN 'CONGIUNZIONI'
WHEN datalength(biglietti.Destinazione_Normalizzata)
= 0 THEN 'NON INDICATA' WHEN biglietti.Destinazione_Normalizzata LIKE 'OR.ISSUE%' THEN 'RIEMISSIONI' ELSE RIGHT(biglietti.Destinazione_Normalizzata, 3) END AS Ritorno, biglietti.Mese_Fiscale,
biglietti.Destinazione_Normalizzata, biglietti.CodiceBiglietto
FROM dbo.Biglietti AS biglietti INNER JOIN
dbo.Compagnie AS compagnie ON biglietti.CodiceCompagnia = compagnie.Codice
WHERE (biglietti.DataEmissione >= DATEADD(year, - 3, GETDATE()))
And the other Views are similar.
Each is needed to performs calculations columns added with each Views.
However i reckon it's a bit inefficient.
How you would solve this?

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