Convert column to row and sum query in different table - sql

i trying to figure to convert sumtchtraffic and totalpayloadGb column in sitetable and sum data totalpayloadGb & sumtchtraffic where BTS_TYPE 2g, 3g and 4g in techtable
i tried like this, but i cant show totalpayloadgb & sumtchtraffic in column [SUM OF] ([sum of] is not in any table in my database)
select * from (select
sum(case when techtable.BTS_TYPE='2G' then sitetable.TotalPayloadGb else 0 end) as [Total 2G],
sum(case when techtable.BTS_TYPE='3G' then sitetable.TotalPayloadGb else 0 end) as [Total 3G],
sum (case when techtable.BTS_TYPE='4G'then sitetable.TotalPayloadGb else 0 end) as [Total 4G]
from sitetable
inner join techtable on sitetable.sitename = techtable.sitename) as t
I want show my data like this:

One way would be to total your results separately, using the same conditional aggregation you have started, and then UNION the results together. Since your first column doesn't exist anywhere else, you'll have to hard-code it into the queries.
SELECT
'TotalPayloadGb' AS SumOf,
sum(CASE WHEN t.BTS_TYPE = '2G' THEN s.TotalPayloadGb ELSE 0 END) AS [Total 2G],
sum(CASE WHEN t.BTS_TYPE = '3G' THEN s.TotalPayloadGb ELSE 0 END) AS [Total 3G],
sum(CASE WHEN t.BTS_TYPE = '4G' THEN s.TotalPayloadGb ELSE 0 END) AS [Total 4G]
FROM sitetable AS s
INNER JOIN techtable AS t
ON s.sitename = t.sitename
UNION
SELECT
'SumTCHTraffic' AS SumOf,
sum(CASE WHEN t.BTS_TYPE = '2G' THEN s.SumTCHTraffic ELSE 0 END) AS [Total 2G],
sum(CASE WHEN t.BTS_TYPE = '3G' THEN s.SumTCHTraffic ELSE 0 END) AS [Total 3G],
sum(CASE WHEN t.BTS_TYPE = '4G' THEN s.SumTCHTraffic ELSE 0 END) AS [Total 4G]
FROM sitetable AS s
INNER JOIN techtable AS t
ON s.sitename = t.sitename;

Depending on what you are trying to do, you could do like this:
SELECT tt.BTS_Type, sum(st.TotalPayloadDb)
FROM SiteTable st
INNER JOIN TechTable as tt on st.sitename = tt.sitename
This will give one row per BTS_Type value.

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().

Update a complex SQL query to add a new column with the sum of two columns

The below SQL query creates a table with n number of columns named in the next line.
...., curr_amount, tax_amount, ....
I am having a very tough time updating the below query to create a new column called total and position it exactly after tax_amount column and the total column should contain the values that are obtained after sum of curr_amount & tax_amount.
I have been working on this from more than one day but couldn't figure it out.
P.S. Still a noob here. Thanks alot for your time.
.
SELECT Isnull(t.total_month, 'Total') total_month,
t.tax_amount,
t.curr_amount,
t.usage_qty,
t.kh_qty,
t.bill_cnt
FROM (SELECT dbo.Sigmadf(bm.posted_date, 'YYYY-MM') total_month,
Sum(CASE
WHEN rr.usage_qty IS NULL THEN 0
ELSE Cast (rr.usage_qty AS NUMERIC(18, 2))
END) usage_qty,
Sum(CASE
WHEN bm.curr_amount IS NULL THEN 0
ELSE bm.curr_amount
END) curr_amount,
Sum(CASE
WHEN bm.adj_amount IS NULL THEN 0
ELSE bm.adj_amount
END) adj_amount,
Sum(CASE
WHEN bm.bal_fwd_amount IS NULL THEN 0
ELSE bm.bal_fwd_amount
END) bal_forward,
Sum(CASE
WHEN bm.tax_amount IS NULL THEN 0
ELSE bm.tax_amount
END) tax_amount,
Sum(CASE
WHEN bm.due_amount IS NULL THEN 0
ELSE bm.due_amount
END) due_amount,
Sum(CASE
WHEN bm.last_total_paid_amount IS NULL THEN 0
ELSE bm.last_total_paid_amount * -1
END) paid_amount,
Sum(CASE
WHEN bm.bill_print = 'Y' THEN 1
ELSE 0
END) pdf_cnt,
Sum(CASE
WHEN Isnull(bm.bill_handling_code, '0') = '0' THEN 1
ELSE 0
END) reg_cnt,
Sum(CASE
WHEN Isnull(bm.bill_handling_code, '0') = '1' THEN 1
ELSE 0
END) ftime_cnt,
Sum(CASE
WHEN Isnull(bm.bill_handling_code, '0') = '9999' THEN 1
ELSE 0
END) ltime_cnt,
Count(*) bill_cnt,
Sum(CASE
WHEN bill_status = '01' THEN 1
ELSE 0
END) canc_cnt,
Sum(CASE
WHEN bill_status = '01' THEN
CASE
WHEN rr.usage_qty IS NULL THEN 0
ELSE Cast (rr.usage_qty AS NUMERIC(18, 2))
END
ELSE 0
END) canc_usg,
Sum(CASE
WHEN vis.kh_qty IS NULL THEN 0
ELSE Cast(vis.kh_qty AS NUMERIC(18, 2))
END) kh_qty
FROM bill_master bm WITH (nolock)
INNER JOIN (SELECT bill_no,
Sum(CASE
WHEN vpb.recurr_charge_type IN ( 'T4',
'SLF' )
THEN
CASE
WHEN vpb.print_qty = 'Y'
AND vpb.usage_qty IS NOT NULL
THEN
Cast (vpb.usage_qty AS
NUMERIC(18, 2))
ELSE 0
END
ELSE 0
END) usage_qty
FROM v_print_bills_all vpb
GROUP BY bill_no) rr
ON rr.bill_no = bm.bill_no
LEFT OUTER JOIN vis_bill_master_cr vis WITH (nolock)
ON bm.bill_no = vis.bill_no
WHERE 1 = 1
AND dbo.Trunc(bm.posted_date) >= '20150101'
AND dbo.Trunc(bm.posted_date) <= '20151124'
AND bm.posted_date IS NOT NULL
AND bm.cust_id NOT IN (SELECT cc.code_type cust_id
FROM code_table cc WITH (nolock)
WHERE cc.code_tabname = 'RptExclCust'
AND cc.code_value = 'cust_id')
GROUP BY dbo.Sigmadf(bm.posted_date, 'YYYY-MM') WITH rollup)t
I must say that the explanation is not so clear.
From my understanding, you want the total of two columns.
So, wrap all your query between parenthesis, call it subQuery, and make the sum of the two columns on top:
SELECT subQuery.total_month as bill_date,
subQuery.curr_amount as amount,
subQuery.tax_amount tax,
subQuery.curr_amount + subQuery.tax_amount as [total],
...
FROM
(..your entire query here..) as subQuery

Speed up glacial sql statement?

I am writing a report that performs a join on three tables.
PartitionCode has about 127 rows.
AcctListLocal has about 17,000 rows.
TrialBal has, ahem, 70,000,000+ rows
The DBMS is Sybase 15
This is taking forever to execute - over 45 mins. It is a development server used by other teams, but still I don't think it's execution time will be acceptable.
All tables have composite PKs -
AcctListLocal (PK and Index)
=============
acct_local
lv1
lv2
entity_code
PartitonCode (PK and Index)
============
entity_code
partition_code
TrialBal (PK + 3 indexes)
========
**PK/Index 1**
ac_cp
ac_gl
ac_gl_ctrl
ac_taps
code
ccy
id
company
co_ta
cc
entity_code
partition_code
pl_date
pro_num
src
**Index 2**
pl_date
entity_code
pro_num
**Index 3**
pl_date
entity_code
company
ac_gl
**Index 4**
pnl_date
entity_code
partition_code
Is part of my problem I'm joining on incomplete indexes - that is, all the indexes are 'composite' fields, but I'm only matching on a couple of them? do i create indexes on
Trial balance consisting on entity_code and partition_code to match to PartitonCode
and
AccListLocal on entity_code and ac_gl to match the lookup to RegalTrialBal
Or are the CASE statements just horrendous?
SQL is below:
INSERT INTO #VolumesAndValues
SELECT
ahl.lv1 AS base,
ahl.lv2 AS ap,
ahl.lv3 AS mc1,
sum(tb.us) as total,
SUM(CASE WHEN pc.partition_lv2 = 'MA' THEN tb.us ELSE 0 END) AS base,
SUM(CASE WHEN pc.partition_lv2 = 'AJ' THEN tb.us ELSE 0 END) AS batch,
SUM(CASE WHEN pc.partition_lv2 in('ADCG','ADIG') AND 1=1 THEN rtb.us ELSE 0 END) AS net,
SUM(CASE WHEN pc.partition_lv2 = 'FR' THEN tb.us ELSE 0 END) AS fr,
SUM(CASE WHEN pc.partition_lv2 = 'PA' THEN tb.us ELSE 0 END) AS pa,
SUM(CASE WHEN pc.partition_lv2 = 'RE' THEN tb.us ELSE 0 END) AS re,
SUM(CASE WHEN pc.partition_lv2 = 'OF' THEN tb.us ELSE 0 END) AS of,
SUM(CASE WHEN pc.partition_lv2 = 'PR' THEN tb.us ELSE 0 END) AS pr,
'1 Table Data' as rowType
FROM TrialBal tb
LEFT OUTER JOIN AcctListLocal al ON tb.entity_code = al.entity_code
and tb.ac_gl_c = al.ac_local
LEFT OUTER JOIN PartitionCode pc ON pc.partition_code = tb.partition_code
GROUP BY al.lv1, al.lv2, al.lv3
If the data structure allows it, perform your aggregation BEFORE all of your case statements, for example:
INSERT INTO #VolumesAndValues
SELECT
base
,ap
,mc1
,plv2
,sum(subtotal) as total
,SUM(CASE WHEN plv2 = 'MA' THEN subtotal ELSE 0 END) AS base
,SUM(CASE WHEN plv2 = 'AJ' THEN subtotal ELSE 0 END) AS batch
,SUM(CASE WHEN plv2 in('ADCG','ADIG') AND 1=1 THEN othersubtotal ELSE 0 END) AS net
,SUM(CASE WHEN plv2 = 'FR' THEN subtotal ELSE 0 END) AS fr
,SUM(CASE WHEN plv2 = 'PA' THEN subtotal ELSE 0 END) AS pa
,SUM(CASE WHEN plv2 = 'RE' THEN subtotal ELSE 0 END) AS re
,SUM(CASE WHEN plv2 = 'OF' THEN subtotal ELSE 0 END) AS of
,SUM(CASE WHEN plv2 = 'PR' THEN subtotal ELSE 0 END) AS pr
,'1 Table Data' as rowType
FROM (
SELECT
ahl.lv1 AS base
,ahl.lv2 AS ap
,ahl.lv3 AS mc1
,pc.partition_lv2 as plv2
,sum(tb.us) as subtotal
,sum(rtb.us) as othersubtotal
FROM TrialBal tb
LEFT OUTER JOIN AcctListLocal al ON tb.entity_code = al.entity_code
and tb.ac_gl_c = al.ac_local
LEFT OUTER JOIN PartitionCode pc ON pc.partition_code = tb.partition_code
GROUP BY
al.lv1
,al.lv2
,al.lv3
,pc.partition_lv2
) subq
GROUP BY
base
,ap
,mc1
,plv2

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