I have the following query:
select'Amount' as Amount,
('£'+ CAST(SUM(rc.[Fee Charge] +rc.[Fee Charge VAT] +rc.ExtraCharges+rc.ExtraChargesVAT+rc.OtherCharges+rc.OtherChargesVAT+rc.WaitingCharge+rc.[WaitingCharge VAT])AS nvarchar(50))) AS [CompletedTurnover],
('£'+ CAST(SUM(rin.[Fee Charge] +rin.[Fee Charge VAT] +rin.ExtraCharges+rin.ExtraChargesVAT+rin.OtherCharges+rin.OtherChargesVAT+rin.WaitingCharge+rin.[WaitingCharge VAT])AS nvarchar(50))) AS [In Progress Turnover],
('£'+ CAST(SUM(run.[Fee Charge] +run.[Fee Charge VAT] +run.ExtraCharges+rc.ExtraChargesVAT+run.OtherCharges+run.OtherChargesVAT+run.WaitingCharge+run.[WaitingCharge VAT])AS nvarchar(50))) AS [Unallocated Turnover],
123 as [Credit Note Value]
from tblreservation R
left join tblreservation rc on R.ReservationsID = rc.reservationsid and rc.Completed = 1
left join tblreservation rin on R.reservationsid = rin.reservationsid and rin.InProgress = 1
left join tblreservation run on Run.ReservationsID = r.ReservationsID and run.completed = 0 and run.inprogress = 0
This returns data like so:
CompletedTurnover In progress Turnover Unallocated Turnover Credit Note Value
1202039920 23998858945 9384585845 123
This is as expected. However, I need the following output and I'm struggling a bit using pivots.
Completed Turnover 1202039920
In Progress Turnover 23998858945
Unallocated Turnover 9384585845
Credit Note Value 123
Any help would be greatly appreciated.
This process to convert columns into rows is actually called an UNPIVOT. You can do this a few different ways.
UNPIVOT: function:
;with cte as
(
select'Amount' as Amount,
('£'+ CAST(SUM(rc.[Fee Charge] +rc.[Fee Charge VAT] +rc.ExtraCharges+rc.ExtraChargesVAT+rc.OtherCharges+rc.OtherChargesVAT+rc.WaitingCharge+rc.[WaitingCharge VAT])AS nvarchar(50))) AS [CompletedTurnover],
('£'+ CAST(SUM(rin.[Fee Charge] +rin.[Fee Charge VAT] +rin.ExtraCharges+rin.ExtraChargesVAT+rin.OtherCharges+rin.OtherChargesVAT+rin.WaitingCharge+rin.[WaitingCharge VAT])AS nvarchar(50))) AS [In Progress Turnover],
('£'+ CAST(SUM(run.[Fee Charge] +run.[Fee Charge VAT] +run.ExtraCharges+rc.ExtraChargesVAT+run.OtherCharges+run.OtherChargesVAT+run.WaitingCharge+run.[WaitingCharge VAT])AS nvarchar(50))) AS [Unallocated Turnover],
123 as [Credit Note Value]
from tblreservation R
left join tblreservation rc
on R.ReservationsID = rc.reservationsid
and rc.Completed = 1
left join tblreservation rin
on R.reservationsid = rin.reservationsid
and rin.InProgress = 1
left join tblreservation run
on Run.ReservationsID = r.ReservationsID
and run.completed = 0
and run.inprogress = 0
)
select col, value
from cte
unpivot
(
value
for col in (CompletedTurnover, [In Progress Turnover],
[Unallocated Turnover], [Credit Note Value])
) u;
CROSS APPLY with VALUES:
;with cte as
(
select'Amount' as Amount,
('£'+ CAST(SUM(rc.[Fee Charge] +rc.[Fee Charge VAT] +rc.ExtraCharges+rc.ExtraChargesVAT+rc.OtherCharges+rc.OtherChargesVAT+rc.WaitingCharge+rc.[WaitingCharge VAT])AS nvarchar(50))) AS [CompletedTurnover],
('£'+ CAST(SUM(rin.[Fee Charge] +rin.[Fee Charge VAT] +rin.ExtraCharges+rin.ExtraChargesVAT+rin.OtherCharges+rin.OtherChargesVAT+rin.WaitingCharge+rin.[WaitingCharge VAT])AS nvarchar(50))) AS [In Progress Turnover],
('£'+ CAST(SUM(run.[Fee Charge] +run.[Fee Charge VAT] +run.ExtraCharges+rc.ExtraChargesVAT+run.OtherCharges+run.OtherChargesVAT+run.WaitingCharge+run.[WaitingCharge VAT])AS nvarchar(50))) AS [Unallocated Turnover],
123 as [Credit Note Value]
from tblreservation R
left join tblreservation rc
on R.ReservationsID = rc.reservationsid
and rc.Completed = 1
left join tblreservation rin
on R.reservationsid = rin.reservationsid
and rin.InProgress = 1
left join tblreservation run
on Run.ReservationsID = r.ReservationsID
and run.completed = 0
and run.inprogress = 0
)
select col, value
from cte
cross apply
(
values
('CompletedTurnover', CompletedTurnover),
('In Progress Turnover', [In Progress Turnover]),
('Unallocated Turnover', [Unallocated Turnover]),
('Credit Note Value', [Credit Note Value])
) c (col, value)
You can use a union to get the results you need:
select 'Completed turnover' Description,
( '£'+ CAST(SUM(rc.[Fee Charge] +
rc.[Fee Charge VAT] +
rc.ExtraCharges+
rc.ExtraChargesVAT+
rc.OtherCharges+
rc.OtherChargesVAT+
rc.WaitingCharge+
rc.[WaitingCharge VAT]
)AS nvarchar(50))) value
from ....
union all
select 'In Progress turnover', .....
from ....
union all
select 'Unallocated Turnover', .....
from ....
you probably want to look at using in conjunction with a CTE
Try this,,,,,
select'Amount' as Amount
union all
select
('£'+ CAST(SUM(rc.[Fee Charge] +rc.[Fee Charge VAT] +rc.ExtraCharges+rc.ExtraChargesVAT+rc.OtherCharges+rc.OtherChargesVAT+rc.WaitingCharge+rc.[WaitingCharge VAT])AS nvarchar(50))) AS [CompletedTurnover]
from tblreservation rc where Completed=1
union all
select
('£'+ CAST(SUM(rin.[Fee Charge] +rin.[Fee Charge VAT] +rin.ExtraCharges+rin.ExtraChargesVAT+rin.OtherCharges+rin.OtherChargesVAT+rin.WaitingCharge+rin.[WaitingCharge VAT])AS nvarchar(50))) AS [In Progress Turnover]
from tblreservation rin where InProgress=1
union all
select
('£'+ CAST(SUM(run.[Fee Charge] +run.[Fee Charge VAT] +run.ExtraCharges+rc.ExtraChargesVAT+run.OtherCharges+run.OtherChargesVAT+run.WaitingCharge+run.[WaitingCharge VAT])AS nvarchar(50))) AS [Unallocated Turnover]
from tblreservation run where InProgress=0 and Completed=0
union all
select 123 as [Credit Note Value]
You probably don't need the joins since the aggregate results come from the same table. You could instead use conditional aggregation
SELECT
SUM(CASE WHEN Completed = 1 THEN
[Fee Charge] + [Fee Charge VAT] + ExtraCharges + ExtraChargesVAT +
OtherCharges + OtherChargesVAT + WaitingCharge + [WaitingCharge VAT]
END) AS [Completed Turnover],
SUM(CASE WHEN InProgress = 1 THEN
...
END) AS [In-progress Turnover],
SUM(CASE WHEN Completed = 0 AND InProgress = 0 THEN
...
END) AS [Unallocated Turnover],
123 AS [Credit Note Value]
FROM tblreservation
and then unpivot the results using either of the methods in #bluefeet's answer:
SELECT
Caption,
Value
FROM (
SELECT
SUM(CASE WHEN Completed = 1 THEN
[Fee Charge] + [Fee Charge VAT] + ExtraCharges + ExtraChargesVAT +
OtherCharges + OtherChargesVAT + WaitingCharge + [WaitingCharge VAT]
END) AS [Completed Turnover],
SUM(CASE WHEN InProgress = 1 THEN
...
END) AS [In-progress Turnover],
SUM(CASE WHEN Completed = 0 AND InProgress = 0 THEN
...
END) AS [Unallocated Turnover],
123 AS [Credit Note Value]
FROM tblreservation
) AS s
UNPIVOT (
Value FOR Caption IN (
[Completed Turnover], [In-progress Turnover],
[Unallocated Turnover], [Credit Note Value]
)
) AS u
;
On the other hand, if InProgress and Completed are always either 1 or 0 and they have consistent values in that they cannot both be 1, you could group the results like this:
SELECT
Completed,
InProgress,
SUM(
[Fee Charge] + [Fee Charge VAT] + ExtraCharges + ExtraChargesVAT +
OtherCharges + OtherChargesVAT + WaitingCharge + [WaitingCharge VAT]
) AS Value
FROM tblreservation
GROUP BY
Completed,
InProgress
The next step would be to turn the combinations of Completed and InProgress into proper captions. One method is to use CASE:
SELECT
CASE
WHEN Completed = 1 THEN 'Completed Turnover'
WHEN InProgress = 1 THEN 'In-progress Turnover'
ELSE 'Unallocated Turnover'
END AS Caption
SUM(
[Fee Charge] + [Fee Charge VAT] + ExtraCharges + ExtraChargesVAT +
OtherCharges + OtherChargesVAT + WaitingCharge + [WaitingCharge VAT]
) AS Value
FROM tblreservation
GROUP BY
Completed,
InProgress
And then you would just add the constant Credit Note Value with a UNION ALL:
SELECT
CASE
WHEN Completed = 1 THEN 'Completed Turnover'
WHEN InProgress = 1 THEN 'In-progress Turnover'
ELSE 'Unallocated Turnover'
END AS Caption
SUM(
[Fee Charge] + [Fee Charge VAT] + ExtraCharges + ExtraChargesVAT +
OtherCharges + OtherChargesVAT + WaitingCharge + [WaitingCharge VAT]
) AS Value
FROM tblreservation
GROUP BY
Completed,
InProgress
UNION ALL
SELECT
'Credit Note Value',
123
;
Related
I am trying to find the difference between the revenue of customers who have not churned vs customers who have. This is what I have:
Select sum ([monthly charge]) as Non_Churned_Revenue
from portfolioproject..telecom_churn
Where [Customer Status] = 'Joined' OR [Customer Status] = 'Stayed'
Select sum ([monthly charge]) as Churned_Revenue
from portfolioproject..telecom_churn
Where [Customer Status] = 'Churned'
How would I be able to subtract Churned_Revenue from Non_Churned_Revenue? I keep getting errors when I try.
Thanks!
You are looking for conditional aggregation
SELECT
SUM(CASE WHEN tc.[Customer Status] IN ('Joined', 'Stayed') THEN tc.[monthly charge] END) AS Non_Churned_Revenue
SUM(CASE WHEN tc.[Customer Status] = 'Churned' THEN tc.[monthly charge] END) AS Churned_Revenue,
SUM(CASE WHEN tc.[Customer Status] IN ('Joined', 'Stayed') THEN tc.[monthly charge] END)
-
SUM(CASE WHEN tc.[Customer Status] = 'Churned' THEN tc.[monthly charge] END) AS Difference
FROM telecom_churn tc;
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.
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.
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.
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.