SQL Query to View - sql

I am trying to turn the following query into a view, however I receive the following execution error:
Can anyone pinpoint where I am going wrong?
Should look like:
Financial Year VOLUME # Cases 5mins # Cases 10mins # Cases 15mins # Cases 20mins
2014/15 1490200 1029 6732 10163 11798
2015/16 1548700 1143 7286 10693 12338
etc...
Code:
SELECT t1.[Financial Year], t1.[VOLUME], t2.[# Cases 5mins], t3.[# Cases 10mins], t4.[# Cases 15mins], t5.[# Cases 20mins]
FROM
(SELECT [Financial Year], CAST(COUNT([Event Number]) AS DECIMAL) *100 as 'VOLUME' FROM tblCAD
WHERE [AO-NonPublicEvent] = 1 AND [Reporting Exclusions] = 0 AND [Reporting Priority] = '1'
GROUP BY [Financial Year]) t1
left join
(SELECT [Financial Year], CAST(COUNT([Event Number]) AS DECIMAL) as '# Cases 5mins' from tblCAD
WHERE [AO-NonPublicEvent] = 1 AND [Reporting Exclusions] = 0 AND CAST([Response Time] AS DECIMAL(9,2))/60 <= 5 AND [Reporting Priority] = '1'
GROUP BY [Financial Year]) t2
ON (t1.[Financial Year] = t2.[Financial Year])
left join
(SELECT [Financial Year], CAST(COUNT([Event Number]) AS DECIMAL) as '# Cases 10mins' from tblCAD
WHERE [AO-NonPublicEvent] = 1 AND [Reporting Exclusions] = 0 AND CAST([Response Time] AS DECIMAL(9,2))/60 <= 10 AND [Reporting Priority] = '1'
GROUP BY [Financial Year]) t3
on (t1.[Financial Year] = t3.[Financial Year])
left join
(SELECT [Financial Year], CAST(COUNT([Event Number]) AS DECIMAL) as '# Cases 15mins' from tblCAD
WHERE [AO-NonPublicEvent] = 1 AND [Reporting Exclusions] = 0 AND CAST([Response Time] AS DECIMAL(9,2))/60 <= 15 AND [Reporting Priority] = '1'
GROUP BY [Financial Year]) t4
on (t1.[Financial Year] = t4.[Financial Year])
left join
(SELECT [Financial Year], CAST(COUNT([Event Number]) AS DECIMAL) as '# Cases 20mins' from tblCAD
WHERE [AO-NonPublicEvent] = 1 AND [Reporting Exclusions] = 0 AND CAST([Response Time] AS DECIMAL(9,2))/60 <= 20 AND [Reporting Priority] = '1'
GROUP BY [Financial Year]) t5
on (t1.[Financial Year] = t5.[Financial Year])

I'm not sure why your code isn't working. But it can be significantly simplified using conditional aggregation and then it will probably work:
SELECT [Financial Year],
COUNT(*) * 100 as VOLUME,
SUM(CASE WHEN CAST([ Response Time ] AS DECIMAL(9, 2)) / 60 <= 5 THEN 1 ELSE 0 END) as within_5_minutes,
SUM(CASE WHEN CAST([ Response Time ] AS DECIMAL(9, 2)) / 60 <= 10 THEN 1 ELSE 0 END) as within_10_minutes,
. . .
FROM tblCAD
WHERE [AO-NonPublicEvent] = 1 AND
[Reporting Exclusions] = 0 AND
[Reporting Priority] = '1'
GROUP BY [Financial Year];
Note that you should fix your column names so they don't need to be escaped. I would suggest something like Fiscal_Year, AO_NonPublic_Event, Reporting_Exclusions, and so on.
I'm also not sure why you are multiplying the first count by 100. And the above assumes that [Event Number] is not NULL. If that is the case, then you need to take that into account.

Related

Messy SQL Query Needs to be more Efficient

THIS Data pull needs help. The efficiency/performance sucks and I don't know enough about SQL to make it better. I'm in the middle of a project that required me to learn SQL pretty fast, but considering the time frame I'm looking at, I've come to YOU, the PROS.... Any ideas from the pros to make this for efficient?
SELECT
d.[Date] AS [Date],
LEFT(CONVERT(VARCHAR,d.[Date],112),6) AS [YearMo],
FORMAT(d.[Date],'MMMM') AS [Month],
YEAR(d.[Date]) AS [Year],
e.[MbrNo] AS [Member ID],
e.[Mkt_State] AS [Mkt State],
e.[Mkt] AS [Mkt Segment],
COALESCE(e.[Individual_Premium_Amt],0) AS [Individual Premium],
COALESCE(e.[Total_Premium_Amt],0) AS [Total Premium],
COALESCE(v.[Inpatient_Pd],0) AS [Inpatient Pd],
COALESCE(v.[Outpatient_Pd],0) AS [Outpatient Pd],
COALESCE(v.[Professional_Pd],0) AS [Professional Pd],
COALESCE(v.[Other_Pd],0) AS [Other Pd],
COALESCE(v.[Med_Pd],0) AS [Med Pd],
COALESCE(SUM(v.[Med_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date])),0) AS [Total Med Pd YTD],
COALESCE(v.[Med_Allowed],0) AS [Med Allowed],
COALESCE(v.[Rx_Pd],0) AS [Rx Pd],
COALESCE(SUM(v.[Rx_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date])),0) AS [Total RX Pd YTD],
COALESCE(v.[Rx_Allowed],0) AS [Rx Allowed],
COALESCE(v.[Med_RX_Pd],0) AS [Med Rx Pd],
COALESCE(SUM(v.[Med_Pd] + v.[Rx_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date])
ORDER BY e.[MbrNo],LEFT(CONVERT(VARCHAR,d.[Date],112),6) ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW),0) AS [RS Med Rx Pd],
COALESCE(SUM(v.[Med_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date]))
+ SUM(v.[Rx_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date])),0) AS [Total Pd YTD],
COALESCE(v.[Med_RX_Allowed],0) AS [Med Rx Allowed],
CASE
WHEN ((SUM(v.[Med_Pd] + v.[Rx_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date]))) > rr.[Recover_Threshold])
THEN ((SUM(v.[Med_Pd] + v.[Rx_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date])) - rr.[Recover_Threshold]))
ELSE 0
END AS [Recoverable Amt],
SUM(1.0) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date])) AS [MM (Yearly)],
CASE
WHEN ((SUM(v.[Med_Pd] + v.[Rx_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date]))) > rr.[Recover_Threshold])
THEN ((SUM(v.[Med_Pd] + v.[Rx_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date])) - rr.[Recover_Threshold]))
/ SUM(1.0) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date]))
ELSE 0
END AS [Recoverable Amtv2],
COALESCE(rr.[Members],0) AS [Members],
COALESCE(rr.[MM],0) AS [MM],
COALESCE(rr.[Rx_Rebates],0) AS [Rx Rebates],
COALESCE(rr.[RA_PMPM],0) AS [RA PMPM],
COALESCE(rr.[RA_Payable],0) AS [RA Payable],
COALESCE(rr.[Pd_Threshold],0) AS [SR Pd Threshold],
COALESCE(rr.[Recover_Threshold],0) AS [SR Recover Threshold],
COALESCE(rr.[CF_Inpatient_PMPM],0) AS [CF IP PMPM],
COALESCE(rr.[CF_Outpatient_PMPM],0) AS [CF OP PMPM],
COALESCE(rr.[CF_Professional_PMPM],0) AS [CF PROF PMPM],
COALESCE(rr.[CF_RX_PMPM],0) AS [CF RX PMPM],
COALESCE(rr.[CF_Med_PMPM],0) AS [CF Med PMPM],
COALESCE(SUM(rr.[CF_RX_PMPM])+(rr.[CF_Med_PMPM]),0) AS [CF Med_Rx PMPM]
FROM -- Date Scaffold - Each month starting 20170101 to the current GETDATE() month
(SELECT
DATEADD(MONTH,number,'20190101') AS [Date],
EOMONTH(DATEADD(MONTH,number,'20190101')) AS [EOM Date]
FROM MASTER..[spt_values]
WHERE TYPE='P'
AND DATEADD(MONTH,number,'20190101') <= GETDATE()
) AS d
INNER JOIN -- Join Med enrollment for each month to the date scaffold, creating the membermonths format
(SELECT
e.*
FROM [SomeDB].[dbo].[sometable] AS e
WHERE [benefitType]=930700000
AND e.[LOB]='Commercial'
AND e.[Segment_Cancelled]<>'Yes'
AND e.[Mbr_Status]<>'Pending Binder Payment'
AND e.[MbrNo]<>0
) AS e
ON e.[Start_Date]<=d.[Date] AND e.[End_Date]>=d.[EOM Date]
LEFT JOIN
(SELECT
c.[YEARMO],
c.[MEMBERID],
SUM(CASE WHEN c.[UTILGRP]='INPATIENT' THEN c.[Pd] ELSE 0 END) AS [Inpatient_Pd],
SUM(CASE WHEN c.[UTILGRP]='OUTPATIENT' THEN c.[Pd] ELSE 0 END) AS [Outpatient_Pd],
SUM(CASE WHEN c.[UTILGRP]='PROFESSIONAL' THEN c.[Pd] ELSE 0 END) AS [Professional_Pd],
SUM(CASE WHEN [UTILGRP]='OTHER' THEN c.[Pd] ELSE 0 END) AS [Other_Pd],
SUM(CASE WHEN c.[CLAIMTYPE]='Med' THEN c.[Pd] ELSE 0 END) AS [Med_Pd],
SUM(CASE WHEN c.[CLAIMTYPE]='Med' THEN c.[ALLOWED] ELSE 0 END) AS [Med_Allowed],
SUM(CASE WHEN c.[CLAIMTYPE]='Pharmacy' THEN c.[Pd] ELSE 0 END) AS [Rx_Pd],
SUM(CASE WHEN c.[CLAIMTYPE]='Pharmacy' THEN c.[ALLOWED] ELSE 0 END) AS [Rx_ALlowed],
SUM(CASE WHEN c.[CLAIMTYPE]='Med' OR c.[CLAIMTYPE]='Pharmacy' THEN c.[Pd] ELSE 0 END) AS [Med_RX_Pd],
SUM(CASE WHEN c.[CLAIMTYPE]='Med' OR c.[CLAIMTYPE]='Pharmacy' THEN c.[ALLOWED] ELSE 0 END) AS [Med_RX_Allowed]
FROM [SomeDB].[dbo].[SomeTable] AS c
WHERE c.[MbrNo] <> 0
AND c.[CLAIMLINESTATUS] NOT IN ('D','V')
AND c.[LOB]='IND'
GROUP BY c.[YearMo],c.[MbrNo]
) AS v
ON e.[MbrNo]=v.[MbrNo] AND LEFT(CONVERT(VARCHAR,d.[Date],112),6)=v.[YearMo]
LEFT JOIN [SomeDB].[dbo].[SomeTable] AS rr
ON e.[Mkt_Segment]=rr.[Mkt_Segment] AND LEFT(CONVERT(VARCHAR,d.[Date],112),6)=rr.[YearMo]
GROUP BY d.[Date],e.[MbrNo],e.[Mkt_State],e.[Mkt_Segment],e.[Individual_Premium_Amt],e.[Total_Premium_Amt],
v.[Inpatient_Pd],v.[Outpatient_Pd],v.[Professional_Pd],v.[Other_Pd],v.[Med_Pd],v.[Med_Allowed],v.[Rx_Pd],v.[Rx_Allowed],v.[Med_RX_Pd],v.[Med_RX_Allowed],
rr.[Members],rr.[MM],rr.[Rx_Rebates],rr.[RA_PMPM],rr.[RA_Payable],rr.[Pd_Threshold],rr.[Recover_Threshold],rr.[CF_Inpatient_PMPM],rr.[CF_Outpatient_PMPM],rr.[CF_Professional_PMPM],rr.[CF_RX_PMPM],rr.[CF_Med_PMPM]
I would replace all the <> 0 statements (Which is typically not SARGable) with >0 statements which is Sargable.

get the value of rows from database2 to join in database1

need to get TCOUNT to be included in my table which is grouped by date, in this query, TCOUNT shows same value on every rows, which is not i expect to show. how can i make tcount shows specific value based from the grouped date
SELECT a.PostingDate,a.Net,a.GROSS,a.DISCS,
(
SELECT count(DISTINCT checkno) AS TCOUNT
FROM [10.0.0.165].[MenuEngg].[dbo].GNDSale
WHERE dob BETWEEN '2016-01-01 00:00:00' AND '2016-01-30 00:00:00'
AND branchcode IN ('037')
AND type IN ('31','19')
) as TCOUNT
FROM
( SELECT REPLACE(CONVERT(VARCHAR(20),
CAST(abs(SUM( CASE WHEN [G_L Account No_] IN ('5010', '5011','5020','5030')
AND [Global Dimension 1 Code] = 'BANQUITO' THEN Amount ELSE 0 END)+
SUM( CASE WHEN [G_L Account No_] BETWEEN '5041' AND '5047'
AND [Global Dimension 1 Code] = 'BANQUITO' THEN Amount ELSE 0 END)) AS MONEY),1),'.00','') AS Net,
REPLACE(CONVERT(VARCHAR(20),CAST(abs(SUM(CASE WHEN [G_L Account No_] IN ('5010', '5011','5020','5030')
AND [Global Dimension 1 Code] = 'BANQUITO' THEN Amount ELSE 0 END)) AS MONEY),1),'.00','')as GROSS,
REPLACE(CONVERT(VARCHAR(20),CAST(abs(SUM( CASE WHEN [G_L Account No_] BETWEEN '5041' AND '5047'
AND [Global Dimension 1 Code] = 'BANQUITO' THEN Amount ELSE 0 END)) AS MONEY),1),'.00','')as DISCS,
replace(convert(NVARCHAR,[Posting Date],110),'-','/') AS PostingDate
FROM [The Cravings Group 2013$G_L Entry]
WHERE [Posting Date] BETWEEN '2016-01-01 00:00:00' AND '2016-01-30 00:00:00'
GROUP BY [Posting Date]
) a
write like that:
...
(
SELECT count(DISTINCT checkno) AS TCOUNT
FROM [10.0.0.165].[MenuEngg].[dbo].GNDSale
WHERE dob BETWEEN '2016-01-01 00:00:00' AND '2016-01-30 00:00:00'
AND branchcode IN ('037')
AND type IN ('31','19')
--add this
AND dob = a.[Posting Date]
) as TCOUNT
FROM
( SELECT [Posting Date]
...

How do I case sum a column based on a value - 1?

So I have the following 2 columns
,sum(case when Owner_Faculty_Full_Desc = 'Business and Law Faculty' then 1 else 0 end) [Business Current Year]
,sum(case when Owner_Faculty_Full_Desc = 'Business and Law Faculty' AND Apps.Reporting_Year = (Apps.Reporting_Year - 1) then 1 else 0 end) [Business Previous Year]
Lets say that Apps.ReportingYear is 2011, how to I get the second column to sum all values in 2010? I thought my statement would work but it doesn't seem to be.
Here is the entire query
WITH Equiv_day AS (
SELECT Date_Key, Sem1_Equivalent_Day
FROM [AUTDataWarehouse].[dbo].[Dim_Date]
WHERE Full_Date = CONVERT(DATE, GETDATE())
),
Date_list AS (
SELECT dt.Date_Key, dt.Calendar_Year
FROM [AUTDataWarehouse].[dbo].[Dim_Date] AS dt
INNER JOIN Equiv_day AS ed
ON (ed.Sem1_Equivalent_Day - 1) = dt.Sem1_Equivalent_Day
AND dt.Calendar_Year IN (YEAR(GETDATE()), YEAR(GETDATE())-1, YEAR(GETDATE()) - 2, YEAR(GETDATE()) - 3, YEAR(GETDATE()) - 4, YEAR(GETDATE()) - 5)
),
PYTD_Outcome_by_Application AS (
SELECT
se.Reporting_Year,
f.Student_Demographics_Key,
f.Application_Code,
Outcome_Row = Max(f.Application_Row_Num)
FROM AUTDataWarehouse.dbo.Fact_Admission as f
INNER JOIN AUTDataWarehouse.dbo.Dim_Intake as it
ON it.Intake_Key = f.Intake_Key
AND it.Prog_Intake_Type_Desc = 'Intake'
INNER JOIN AUTDataWarehouse.dbo.Dim_Semester as se
ON se.Semester_Key = f.Semester_Key
INNER JOIN AUTDataWarehouse.dbo.Dim_Campus as cp
ON cp.Campus_Key = f.Campus_Key
INNER JOIN Date_list as dates
ON dates.Calendar_Year = se.Reporting_Year
WHERE f.Last_Change_Date_Key < dates.Date_Key
GROUP BY
se.Reporting_Year,
f.Student_Demographics_Key,
f.Application_Code
),
Applications_Count AS (
SELECT
p.Owner_Faculty_Full_Desc,
p.Programme_Full_Desc,
et.Enrolment_Type_Key,
se.Reporting_Year,
sd.Last_Secondary_School_Name [LastSchoolName],
pr.Programme_Key,
Campus = CASE WHEN cp.Campus_Name IN ('South','South Dist') THEN 'South' ELSE 'City / North Shore' END,
se.Semester_Desc,
f.Student_Demographics_Key,
Applicants = COUNT(DISTINCT f.Student_Demographics_Key)
FROM AUTDataWarehouse.dbo.Fact_Admission as f
INNER JOIN AUTDataWarehouse.dbo.Dim_Student_Demographics as sd ON sd.Student_Demographics_Key = f.Student_Demographics_Key
INNER JOIN AUTDataWarehouse.dbo.Dim_Programme as P on P.Programme_Key = f.Programme_Key
INNER JOIN AUTDataWarehouse.dbo.Dim_Intake as it
ON it.Intake_Key = f.Intake_Key
AND it.Prog_Intake_Type_Desc = 'Intake'
INNER JOIN AUTDataWarehouse.dbo.Dim_Enrolment_Type as et
ON et.Enrolment_Type_Key = f.Enrolment_Type_Key
INNER JOIN AUTDataWarehouse.dbo.Dim_Programme as pr
ON pr.Programme_Key = f.Programme_Key
INNER JOIN AUTDataWarehouse.dbo.Dim_Campus as cp
ON cp.Campus_Key = f.Campus_Key
INNER JOIN AUTDataWarehouse.dbo.Dim_Semester as se
ON se.Semester_Key = f.Semester_Key
INNER JOIN Date_list as dates
ON dates.Calendar_Year = se.Reporting_Year
INNER JOIN PYTD_Outcome_by_Application AS pytd
ON pytd.Application_Code = f.Application_Code
AND pytd.Student_Demographics_Key = f.Student_Demographics_Key
AND pytd.Outcome_Row = f.Application_Row_Num
and pytd.Reporting_Year = se.Reporting_Year
AND pytd.Application_Code IS NOT NULL
GROUP BY
sd.Last_Secondary_School_Name,
p.Owner_Faculty_Full_Desc,
p.Programme_Full_Desc,
et.Enrolment_Type_Key,
se.Reporting_Year,
pr.Programme_Key,
CASE WHEN cp.Campus_Name IN ('South','South Dist') THEN 'South' ELSE 'City / North Shore' END,
se.Semester_Desc,
f.Student_Demographics_Key
)
SELECT
CAST(EP.Educational_Provider_Key as varchar(10)) as 'Education Key'
,[LastSchoolName]
,Owner_Faculty_Full_Desc
,Programme_Full_Desc
,Apps.Reporting_Year
,cast(cast(Apps.Reporting_Year as varchar(255)) + '0101' as datetime) as [YearTime]
,sum(case when Owner_Faculty_Full_Desc = 'Business and Law Faculty' then 1 else 0 end) [Business and Law Current Year]
,sum(case when Owner_Faculty_Full_Desc = 'Business and Law Faculty' AND (Apps.Reporting_Year = Apps.Reporting_Year - 1) then 1 else 0 end) [Business and Law Previous Year]
,sum(case when Owner_Faculty_Full_Desc = 'Culture and Society Faculty' then 1 else 0 end) [Culture and Society Current Year]
,sum(case when Owner_Faculty_Full_Desc = 'Culture and Society Faculty' AND Apps.Reporting_Year = 2014 then 1 else 0 end) [Culture and Society Previous Year]
,sum(case when Owner_Faculty_Full_Desc = 'Design & Creative Technologies Faculty'then 1 else 0 end) [Design & Creative TechnologiesCurrent Year]
,sum(case when Owner_Faculty_Full_Desc = 'Design & Creative Technologies Faculty' AND Apps.Reporting_Year = (Apps.Reporting_Year - 1) then 1 else 0 end) [Design & Creative Technologies Previous Year]
,sum(case when Owner_Faculty_Full_Desc = 'Health & Environmental Sciences Faculty'then 1 else 0 end) [Health & Environmental Sciences Current Year]
,sum(case when Owner_Faculty_Full_Desc = 'Health & Environmental Sciences Faculty' AND Apps.Reporting_Year = (Apps.Reporting_Year - 1) then 1 else 0 end) [Health & Environmental Sciences Previous Year]
,sum(case when Owner_Faculty_Full_Desc = 'Te Ara Poutama' then 1 else 0 end) [Te Ara Poutama Current Year]
,sum(case when Owner_Faculty_Full_Desc = 'Te Ara Poutama' AND Apps.Reporting_Year = (Apps.Reporting_Year - 1) then 1 else 0 end) [Te Ara Poutama Previous Year]
,sum(apps.Applicants) [Total Applicants]
FROM Applications_Count as Apps
inner join AUTDataWarehouse.dbo.Dim_Educational_Provider as EP on EP.Provider_Name = [LastSchoolName]
GROUP BY Apps.Reporting_Year, [LastSchoolName], EP.Educational_Provider_Key,Owner_Faculty_Full_Desc
, Programme_Full_Desc
ORDER BY Apps.Reporting_Year, [Total Applicants] DESC
So basically for each programme I want a column for total applicants for the ReportingYear then total applicants for the Reporting Year - 1
Thanks!
Probably easiest to calculate the years separately, then self-join to get the value for the previous year. This is the basic logic you would use, although obviously you will need to make it more complex when you adapt it to the long query above:
;with CTE as (select ReportingYear
, sum(case when [condition] then 1 else 0 end) as ValueCurrYear
from MyTables
group by ReportingYear)
Select a.*, b.ValueCurrYear as ValuePreviousYear
from CTE a
left join CTE b
on a.ReportingYear = b.ReportingYear + 1

UNION not ouputting correct combined data in SQL/SSRS server 2008

I am a NEWBIE, self taught SQL creator.
I have created a report that uses a series of queries to create 2 temp tables that need joined together.
When I run the report in SQL, I actually get the first temp table as a result, then I get the combined (UNION) result that I want as well.
Then, when I imported this SQL into SSRS and created the pretty report, I'm only getting the results of the FIRST temp table. How do I correct this? Here is the union statement that is supposed to combine the results of the two temp tables.
--declare #StartDate datetime
--declare #EndDate datetime
--declare #FirstGL nvarchar(9)
--declare #LastGL nvarchar(9)
--set #StartDate = '07-01-2014'
--set #EndDate = '02-01-2015'
--------------Temp Table #1 - Pulls invoice detail from AP for a selected time period and selected GL account numbers -------------------
select gl.acc_ext_id as [GL #]
,rtrim(gl.acc_ds) as [Account Descr]
,convert(varchar(10),ih.ivo_dt,101) as [Activity Date]
,((rtrim(vm.org_nm) + ' Inv#: ' + rtrim(ih.ivo_ext_id) + ' ' + (CASE WHEN ih.ivo_ds IS NULL THEN ' ' ELSE rtrim(ih.ivo_ds) END) + (CASE WHEN id.ivo_dtl_ds IS NULL THEN ' ' ELSE rtrim(id.ivo_dtl_ds) END))) as [Journal Descr]
,CAST(id.ivo_prc_at as decimal(12,2)) as [Inv Amt]
into #APDetail
from TAP600_INVOICE_HDR ih inner join TAP650_INVOICE_DTL id on id.ivo_int_id = ih.ivo_int_id
inner join TAP300_VENDOR_MASTER vm on vm.vnd_int_id = ih.vnd_int_id
inner join TGL910_CHART_OF_ACCOUNTS gl on gl.acc_int_id = id.acc_int_id
where gl.acc_ext_id between #FirstGL and #LastGL
and ih.ivo_dt > #StartDate and ih.ivo_dt < #EndDate
order by gl.acc_ext_id, ih.ivo_dt
------------------Temp Table #2 - Takes temp table #APDetail and moves Inv Amt to either DR or CR field and limits length of description to 75 characters
select distinct [GL #]
, [Account Descr]
, [Activity Date]
, [Journal Descr]
, [Inv Amt]
into #APDetailUpdate
from #APDetail
alter table #APDetailUpdate
add Debit decimal(12,2)
update apu
set apu.Debit = ap.[Inv Amt]
from #APDetailUpdate apu left join #APDetail ap on ap.[GL #] = apu.[GL #] and ap.[Account Descr] = apu.[Account Descr] and ap.[Activity Date] = apu.[Activity Date] and ap.[Journal Descr] = apu.[Journal Descr]
where ap.[Inv Amt] > 0 or ap.[Inv Amt] = 0
alter table #APDetailUpdate
add Credit decimal(12,2)
update apu
set apu.Credit = ap.[Inv Amt]
from #APDetailUpdate apu left join #APDetail ap on ap.[GL #] = apu.[GL #] and ap.[Account Descr] = apu.[Account Descr] and ap.[Activity Date] = apu.[Activity Date] and ap.[Journal Descr] = apu.[Journal Descr]
where ap.[Inv Amt]<0
select [GL #]
, [Account Descr]
, [Activity Date]
, [Journal Descr]
--, [Inv Amt]
, [Debit]
, [Credit]
from #APDetailUpdate
order by [GL #], [Activity Date]
--------------Temp Table #3 - Pulls journal entry detail from GL for a selected time period and selected GL account numbers---------------------
select gl.acc_ext_id as [GL #]
,rtrim(gl.acc_ds) as [Account Descr]
,convert(varchar(10),jh.jnl_pst_dt,101) as [Activity Date]
,(CASE WHEN jd.jnl_dtl_ds IS NULL THEN jh.sys_cd + ' - ' + jh.src_ds ELSE jd.jnl_dtl_ds END) as [Journal Descr]
,sum((CASE WHEN jd.jnl_pst_deb_at IS NULL THEN '0.00' ELSE jd.jnl_pst_deb_at END)) as [Debit]
,sum((CASE WHEN jd.jnl_pst_crd_at IS NULL THEN '0.00' ELSE jd.jnl_pst_crd_at END)) as [Credit]
into #GLDetail
from TGL220_JE_HDR jh inner join TGL250_JE_DTL jd on jd.jnl_int_id = jh.jnl_int_id
inner join TGL910_CHART_OF_ACCOUNTS gl on gl.acc_int_id = jd.acc_int_id
where gl.acc_ext_id between #FirstGL and #LastGL
and jh.jnl_pst_dt > #StartDate
and sys_cd <> 'AP'
group by gl.acc_ext_id, gl.acc_ds, jh.jnl_pst_dt,(CASE WHEN jd.jnl_dtl_ds IS NULL THEN jh.sys_cd + ' - ' + jh.src_ds ELSE jd.jnl_dtl_ds END)
order by gl.acc_ext_id, jh.jnl_pst_dt
-----------------------Final Report - Combines the two tables with a Union statement --------------------
select [GL #],
[Account Descr],
[Activity Date],
substring([Journal Descr],1,75),
(CASE WHEN apu.[Debit] IS NULL then 0.00 else apu.[Debit] END) as Debit,
(CASE WHEN apu.[Credit] IS NULL then 0.00 else apu.[Credit] END)as Credit
from #APDetailUpdate apu
UNION
select [GL #],
[Account Descr],
[Activity Date],
substring([Journal Descr],1,75),
(CASE WHEN [Debit] IS NULL then 0 else [Debit] END), (CASE WHEN [Credit] IS NULL then 0 else [Credit] END)
from #GLDetail
order by [GL #], [Activity Date]
Your problem is you're running two select statements:
select [GL #]
, [Account Descr]
, [Activity Date]
, [Journal Descr]
--, [Inv Amt]
, [Debit]
, [Credit]
from #APDetailUpdate
order by [GL #], [Activity Date]
and
select [GL #],
[Account Descr],
[Activity Date],
substring([Journal Descr],1,75),
(CASE WHEN apu.[Debit] IS NULL then 0.00 else apu.[Debit] END) as Debit,
(CASE WHEN apu.[Credit] IS NULL then 0.00 else apu.[Credit] END)as Credit
from #APDetailUpdate apu
UNION
select [GL #],
[Account Descr],
[Activity Date],
substring([Journal Descr],1,75),
(CASE WHEN [Debit] IS NULL then 0 else [Debit] END), (CASE WHEN [Credit] IS NULL then 0 else [Credit] END)
from #GLDetail
order by [GL #], [Activity Date]
SSRS will only ever return the results of the first select to be used as a dataset. You need to choose which one you want to be displayed as the dataset and then run a separate query in another dataset for the other select. Either that or union them all or remove the first select statement.
Hope this helps.

SQL sum or subtracted based on a column (transaction type)

I'm currently trying to get the total quantity delivered for a given security in a SQL table. I want to calculate each line and sum them them up if they are a positive transaction type (+) [txn type] or delete that total from the rest of the results if the transaction type is negative (-). I can currently return the sum for all rows with the following code
SELECT [STOCK REC NO],
SUM(ISNULL([QTY DELIVERED], 0) + ISNULL([QTY DUE IN], 0) - ISNULL([QTY DUE OUT], 0)) AS [TOTAL QUANTITY]
FROM bla_bla
WHERE ([EVENT DATE] < '09/26/2012')
GROUP BY [STOCK REC NO]
TXN TYPE QTY DELIVERED QTY DUE IN QTY DUE OUT EVENT DATE
+ 1 28/11/2005
+ 2 07/02/2006
- 3 22/11/2006
+ 20 18/04/2011
+ 40 19/04/2011
If I understand your question correctly do it this way
SELECT [STOCK REC NO],
SUM(ISNULL(CASE WHEN [TXN TYPE] = '-' THEN -1 ELSE 1 END * [QTY DELIVERED], 0) +
ISNULL(CASE WHEN [TXN TYPE] = '-' THEN -1 ELSE 1 END * [QTY DUE IN], 0) -
ISNULL(CASE WHEN [TXN TYPE] = '-' THEN -1 ELSE 1 END * [QTY DUE OUT], 0))
AS [TOTAL QUANTITY]
FROM bla_bla
WHERE ([EVENT DATE] < '09/26/2012')
GROUP BY [STOCK REC NO]
SELECT [STOCK REC NO],
CASE TXN_TYPE
WHEN '+' THEN SUM(ISNULL([QTY DELIVERED], 0) + ISNULL([QTY DUE IN], 0) + ISNULL([QTY DUE OUT], 0))
ELSE SUM(ISNULL([QTY DELIVERED], 0) + ISNULL([QTY DUE IN], 0) - ISNULL([QTY DUE OUT], 0))
END AS [TOTAL QUANTITY]
FROM bla_bla
WHERE ([EVENT DATE] < '09/26/2012')
GROUP BY
[STOCK REC NO]
If TXN_TYPE is always either + or -, you could try this little trick:
SELECT [STOCK REC NO],
SUM(
(TXN_TYPE + '1') * (
ISNULL([QTY DELIVERED], 0) + ISNULL([QTY DUE IN], 0) - ISNULL([QTY DUE OUT], 0)
)
) AS [TOTAL QUANTITY]
FROM bla_bla
WHERE ([EVENT DATE] < '09/26/2012')
GROUP BY [STOCK REC NO]
TXN_TYPE + '1' becomes either '+1' or '-1'. Although it is a string, it gets implicitly converted to a number because of the multiplication.