Join the results from two queries into one in Oracle SQL - sql

I have two queries and I want to join them without creating a function. The first one gives me the result of my current balance. The result is 160€:
select sum(SESSIONS.PRICE) - sum(SESSIONS.AMOUNT) as v_diff
from SESSIONS
where SESSIONS.CLIENTS_ID =:P2002_ID
and SESSIONS.STATUS in (4,5);
The second query gives the extra payment. The result is 30€:
select sum(SESSIONS.AMOUNT) as v_extra_amount
from SESSIONS
where SESSIONS.CLIENTS_ID = :P2002_ID
and SESSIONS.STATUS = 1
and SESSIONS.PAYMENT_STATUS = 2;
So I want if it is possible one query to give me the amount of 130€! (160€ from the first one -30€ from the second).

Just use conditional aggregation:
select (sum(case when s.STATUS in (4, 5) then s.PRICE else 0 end) -
sum(case when s.STATUS in (4, 5) then s.AMOUNT else 0 end)
),
sum(case when s.STATUS = 2 then s.AMOUNT end)
into v_diff, v_extra_amount
from SESSIONS s
where s.CLIENTS_ID = :P2002_ID;
Or, if you want one value, just subtract:
select (sum(case when s.STATUS in (4, 5) then s.PRICE else 0 end) -
sum(case when s.STATUS in (4, 5) then s.AMOUNT else 0 end) -
sum(case when s.STATUS = 1 and s.PAYMENT_STATUS = 2 then s.AMOUNT end)
)
from SESSIONS s
where s.CLIENTS_ID = :P2002_ID;

Related

SQL Year over Year Performance with Criteria

I am trying to return year over year results based on date criteria. There is additional information I would like to include in the query i.e. first date of activity and first date of activity with spot name like '%6%'. The current query I have is multiplying the correct amounts by 6 and I can't figure out how to solve. When I remove the first "where" clause I get the correct amounts. Any help would be appreciated.
Select
V.IGB_License,
DBA,
V.Sci_Games_Name,
convert(date,v2.Activity_date) as First6thMachineDate,
convert(date,V3.Activity_date) as GoLiveDate,
sum(case when (v.Activity_date between '1/23/2019' and DATEADD(YEAR,-2,getdate()-1)) then v.Funds_in else 0 end) as FundsIn2019,
sum(case when (v.Activity_date between '1/23/2020' and DATEADD(YEAR,-1,getdate()-1)) then v.Funds_in else 0 end) as FundsIn2020,
sum(case when (v.Activity_date between '1/23/2021' and getdate()) then v.Funds_in else 0 end) as FundsIn2021,
sum(case when (v.Activity_date between '1/23/2019' and DATEADD(YEAR,-2,getdate()-1)) then v.Net_funds else 0 end) as NetFunds2019,
sum(case when (v.Activity_date between '1/23/2020' and DATEADD(YEAR,-1,getdate()-1)) then v.Net_funds else 0 end) as NetFunds2020,
sum(case when (v.Activity_date between '1/23/2021' and getdate()) then v.Net_funds else 0 end) as NetFunds2021
From VGT_activity V
Left Join Locations on v.IGB_License = Locations.IGB_License
left join VGT_activity V2 on v.IGB_License = v2.IGB_License
Left join VGT_activity V3 on v.IGB_License = v3.IGB_License
Where v2.Activity_date = (
Select Min(V1.Activity_date)
From VGT_activity V1
Where v1.IGB_License = V2.IGB_License
and Spot_name like '%6%'
)
and v3.Activity_date = (
Select Min(V1.Activity_date)
From VGT_activity V1
Where v1.IGB_License = V3.IGB_License
)
group by V.IGB_License, dba, V.Sci_Games_Name, v2.Activity_date, v3.Activity_date
order by 4

sum case issue , no column for groupby clause

I have the query:
SELECT leads,
touched,
invalid,
TQL,
SQOs,
Wins,
(touched / (CONVERT(decimal(7, 2), leads)) * 100) AS [touch%],
(t.invalid / touched) AS [Invalid Leads%],
(TQL / (CONVERT(decimal(7, 2), touched)) * 100) AS [TQL %],
(SQOs / (CONVERT(decimal(7, 2), TQL)) * 100) AS [SQO%],
(Wins / (CONVERT(decimal(7, 2), TQL)) * 100) AS [Wins%]
FROM (SELECT COUNT([lead id]) AS leads,
SUM(CASE
WHEN a.status = 'Disqualified'
OR a.status = 'Qualified'
AND a.[Status Reason] <> 'Expired' THEN 1
ELSE 0
END) AS touched,
SUM(CASE
WHEN a.status = 'Disqualififed'
AND a.[Status Reason] IN ('Already Engaged', 'Already purchased', 'Invalid Contact Info', 'Misrouted Lead', 'Non-Supported Market', 'Partner') THEN 1
ELSE 0
END) AS invalid,
SUM(CASE WHEN a.status = 'Qualified' THEN 1 ELSE 0 END) AS TQL,
SUM(CASE WHEN b.status = 'Open' THEN 1 ELSE 0 END) AS SQOs,
SUM(CASE WHEN b.status = 'Won' THEN 1 ELSE 0 END) AS Wins,
CASE WHEN b.status = 'Won' THEN SUM([End Cust Purchase Amount Const $])END AS tqlrevenue
FROM lead a
LEFT JOIN opportunity b ON a.[Opportunity Id (Qualifying Opportunity) (Opportunity)] = b.[Opportunity Id]
LEFT JOIN MSSalesMalaysia_Updated c ON b.[Opportunity Id] = c.[opp id]
WHERE a.[Lead Source] = 'Marketing') t;
When I add the expression case when B.status ='Won' then sum([End Cust Purchase Amount Const $]) end as tqlrevenue I get the following error:
Column 'opportunity.Status' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Now all columns in subquery are case conditions, which column to include?
You probably want conditional aggregation:
sum(case when B.status ='Won' then [End Cust Purchase Amount Const $]) end) as tqlrevenue
That is, the case expression is the argument to sum().

BigQuery: group counters by month after self-join

I have table that looks like this:
I'm trying to build a query, that will show specific partnerId counters groupped by keywordName and month.
To solve first part(without grouping by month), I've built this query:
SELECT keywordName, COUNT(keywordName) as total, IFNULL(b.ebay_count, 0) as ebay, IFNULL(c.amazon_count, 0) as amazon,
FROM LogFilesv2_Dataset.FR_Clickstats_v2 a
LEFT JOIN
(SELECT keywordName as kw , SUM(CASE WHEN partnerId='eBay' THEN 1 ELSE 0 END) as ebay_count
FROM LogFilesv2_Dataset.FR_Clickstats_v2
WHERE partnerId = 'eBay' GROUP BY kw) b
ON keywordName = b.kw
LEFT JOIN
(SELECT keywordName as kw , SUM(CASE WHEN partnerId='AmazonApi' THEN 1 ELSE 0 END) as amazon_count
FROM LogFilesv2_Dataset.FR_Clickstats_v2
WHERE partnerId = 'AmazonApi' GROUP BY kw) c
ON keywordName = c.kw
WHERE keywordName = 'flipper' -- just to filter out single kw.
GROUP BY keywordName, ebay, amazon
It works quite well and returns following output:
Now I'm trying to make additional group by month, but all my attempts returned incorrect results.
Final output supposed to be similar to this:
You can do this with conditional aggregation:
select
date_trunc(dt, month) dt,
keywordName,
count(*) total,
sum(case when partnerId = 'eBay' then 1 else 0 end) ebay,
sum(case when partnerId = 'AmazonApi' then 1 else 0 end) amazon
from LogFilesv2_Dataset.FR_Clickstats_v2
group by date_trun(dt, month), keywordName

SQL - How do I simplify this easy query?

I am using SQL Server 2005.
How could I refactor this query?
SELECT Total, Installs, Service, tot.ls_chg_dte_ojb
FROM (SELECT COUNT(*) [Total], ls_chg_dte_ojb
FROM [COMPL_INST_SVC]
GROUP BY ls_chg_dte_ojb) tot
JOIN (SELECT COUNT(*) [Service], ls_chg_dte_ojb
FROM [COMPL_INST_SVC]
WHERE job_class_ojb = 'S'
GROUP BY ls_chg_dte_ojb) svc on svc.ls_chg_dte_ojb = tot.ls_chg_dte_ojb
JOIN (SELECT COUNT(*) [Installs], ls_chg_dte_ojb
FROM [COMPL_INST_SVC]
WHERE job_class_ojb in ('C', 'R')
GROUP BY ls_chg_dte_ojb) ins on ins.ls_chg_dte_ojb = tot.ls_chg_dte_ojb
It looks like the Total and Service counts are counting the same exact thing, so you'll need to fix that, but here's basically how you do the counts in a simpler way:
SELECT
COUNT(CASE WHEN job_class_ojb = 'S' THEN 1 END) AS [Total],
COUNT(CASE WHEN job_class_ojb = 'S' THEN 1 END) AS [Service],
COUNT(CASE WHEN job_class_ojb in ('C', 'R') THEN 1 END) AS [Installs]
FROM
[COMPL_INST_SVC]
Two of your sub-selects are the same. Ignoring the 'Service' one, try something along the lines of
SELECT
SUM(CASE WHEN job_class_ojb = 'S' THEN 1 ELSE 0 END) as Total,
SUM(CASE WHEN job_class_ojb = 'C' or
job_class_ojb = 'R' THEN 1 ELSE 0 END) as Installs
FROM COMPL_INST_SVC
I suspect that the Totals subquery should not include the WHERE job_class_ojb = 'S' condition - if so, I suggest:
SELECT COUNT(*) Total,
SUM(CASE WHEN job_class_ojb = 'S' THEN 1 ELSE 0 END) Service,
SUM(CASE WHEN job_class_ojb in ('C','R') THEN 1 ELSE 0 END) Installs,
ls_chg_dte_ojb
FROM COMPL_INST_SVC
GROUP BY ls_chg_dte_ojb

"Timeout expired" error, when executing view in SQL Server 2008

I've written a query in SQL Server 2008. The query takes about 4 minutes to execute.
I need this query as a View. So, I've created a view with this query and when I try to execute the view creation script, it shows the following error:
Timeout Expired.
The timeout period elapsed prior to completion of the operation or the server is not responding.
The query is:
SELECT t.jrnno,
(SELECT SUM(t1.amount)
FROM dbo.T_sh AS t1
WHERE (t1.b_or_s = '1') AND (t1.jrnno = t.jrnno)) AS buy,
(SELECT SUM(t2.amount)
FROM dbo.T_sh AS t2
WHERE (t2.b_or_s = '2') AND (t2.jrnno = t.jrnno)) AS sale,
SUM(t.amount) AS Total,
SUM(t.h_crg) AS Howla,
SUM(t.l_crg) AS Laga,
SUM(t.taxamt) AS Tax,
SUM(t.commsn) AS Commission
FROM dbo.T_sh AS t
WHERE (t.tran_type = 'S')
AND (t.jrnno NOT IN (SELECT DISTINCT jrnno
FROM dbo.T_ledger))
GROUP BY t.jrnno
T_sh and T_ledger both tables have about 100K rows. What could be the possible reason and how can I overcome this?
Update:
select
t.jrnno,
SUM(CASE WHEN t.b_or_s = 1 THEN t.amount ELSE NULL END) buy,
SUM(CASE WHEN t.b_or_s = 2 THEN t.amount ELSE NULL END) sale,
SUM(t.amount) AS Total,
SUM(t.h_crg) AS Howla,
SUM(t.l_crg) AS Laga,
SUM(t.taxamt) AS Tax,
SUM(t.commsn) AS Commission
FROM
dbo.t_sh t
WHERE
t.tran_type = 'S'
AND NOT EXISTS(SELECT 1 FROM dbo.T_ledger x where x.jrnno = t.jrnno)
group by
t.jrnno
It solved my problem. Thanks everyone for your quick response.
Try this query:
select
t.jrno,
SUM(CASE WHEN t1.b_or_s = 1 THEN t.amount ELSE NULL END) buy,
SUM(CASE WHEN t1.b_or_s = 2 THEN t.amount ELSE NULL END) sale,
SUM(t.amount) AS Total,
SUM(t.h_crg) AS Howla,
SUM(t.l_crg) AS Laga,
SUM(t.taxamt) AS Tax,
SUM(t.commsn) AS Commission
FROM dbo.t_sh t
WHERE t.tran_type = 'S'
AND NOT EXISTS(SELECT 1 FROM dbo.T_ledger x x.jrno = t.jrno)
Your query only needs to scan dbo.T_sh once:
SELECT t.jrnno,
SUM(CASE WHEN t.b_or_s = 1 THEN t.amount ELSE NULL END) AS buy,
SUM(CASE WHEN t.b_or_s = 2 THEN t.amount ELSE NULL END) AS sale,
SUM(t.amount) AS Total,
SUM(t.h_crg) AS Howla,
SUM(t.l_crg) AS Laga,
SUM(t.taxamt) AS Tax,
SUM(t.commsn) AS Commission
FROM dbo.T_sh AS t
WHERE t.tran_type = 'S'
AND t.jrnno NOT IN (SELECT DISTINCT
tl.jrnno
FROM dbo.T_ledger tl)
GROUP BY t.jrnno