get the value of rows from database2 to join in database1 - sql

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]
...

Related

How can I get the difference of 2 variables in Microsoft SQL?

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;

SQL Query to View

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.

Calculating Closing and Opening Balance in SQL

I have a table 'transactions(txDate, amount, txType) where txType can "credit" or "debit".
I need to get an opening and closing balance when returning transactions between two dates.
The first row of the results should be the Opening Balance, then a list of all tx between the dates and the last row to be a Closing balance
Getting the list isn't a train smash but for the balances, I currently have the following
SELECT SUM(amount) AS [Opening Balance]
FROM
(
SELECT SUM([Amount]) amount
FROM [dbo].[Transaction]
WHERE [txDate] <= #startDate
AND [txType] = 'credit'
UNION ALL
SELECT 0 - SUM([Amount]) amount
FROM [dbo].[Transaction]
WHERE [TransactionDate] <= #startDate
AND [txType] = 'debit'
) Transactions
this gives a very big amount than what it should be.
And for the Closing balance, I have no idea how to go about it
You could use CASE in SUM
select sum(case when txType = 'credit' and transactionDate <= #startDate
then amount end) -
sum(case when txType = 'debit' and transactionDate <= #startDate
then amount end)[Opening Balance],
sum(case when txType = 'credit' and transactionDate <= #endDate
then amount end) -
sum(case when txType = 'debit' and transactionDate <= #endDate
then amount end)[Closing Balance]
from transaction

get the row details of other table from another server and merge it to your query

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(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];
this will result into
COLA | COLB
row | row
i would like to add another column from this query
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 branchcode in ('037')and type in ('31','19')
where it should give me cola colb colc, i dont know how will i match [global dimension 1 code] into another database which is using [branch code]? to get or merge them and come up with this result
COLA | COLB | COLC
row | row | row
Try this
SELECT a.Net,a.PostingDate,
(
SELECT count(DISTINCT checkno) AS TCOUNT
FROM [10.0.0.165].[MenuEngg].[dbo].GNDSale
WHERE dob BETWEEN '2016-01-30 00:00:00' AND '2016-01-30 00:00:00'
AND branchcode IN ('037')
AND branchcode IN ('037')
AND TYPE IN ('31','19')
) as COLC
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(NVARCHAR,[Posting Date],110),'-','/') AS PostingDate
FROM [The Cravings Group 2013$G_L Entry]
WHERE [Posting Date] BETWEEN '2016-01-30 00:00:00' AND '2016-01-30 00:00:00'
GROUP BY [Posting Date]
) a

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.