Speed up glacial sql statement? - sql

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

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

Convert column to row and sum query in different table

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.

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

Trying to group several rows based on donatedmoney status

I'm really struggling with this. I just can't seem to figure it out. I've got the concept in my head but don't exactly know how to put my plain language understanding of how to solve the problem into the correct Syntax.
Here is the question.
Give me a list of all donors and their addresses categorized by whether they donated art, money, or both.
Here is the set up for the tables.
CareTakers: CareTakerID, CareTakerName
Donations: DonationID, DonorID, DonatedMoney, ArtName, ArtType, ArtAppraisedPrice, ArtLocationBuilding, ArtLocationRoom, CareTakerID
Donors: DonorID, DonorName, DonorAddress
Here is what I have for my code so far.
SELECT
DISTINCT(DonorName), DonorAddress
FROM
Donors JOIN Donations ON Donors.DonorID = Donations.DonorID
GROUP BY
DonatedMoney
HAVING
DonatedMoney = 'Y' OR DonatedMoney = 'N' OR DonatedMoney = 'Y' AND ArtName IS NOT NULL
Any help would be highly appreciated!
Why would you use a having clause? The question specifies no filtering. The following summarizes the donations to get what you need and then joins the results back to the donors table:
select d.*, don.DonationType
from donors d join
(select don.donorid,
(case when sum(case when donatedmoney = 'Y' then 1 else 0 end) > 0 and
sum(case when artname is not null then 1 else 0 end) > 0
then 'Both'
when sum(case when donatedmoney = 'Y' then 1 else 0 end) > 0
then 'Money'
when sum(case when artname is not null then 1 else 0 end)
then 'Art'
else 'Neither'
end) as DonationType
from donations don
group by don.donorid
) don
on d.donorid = don.donorid

Ways to stop SQL query from displaying a table multiple times?

In my script, I have a table displaying the results of a SQL query. However, I am using the results as a summary, but the SQL is making the page display the table as many times as there are results (rows) in the returning SQL that are allowed because of the Where clause. I.e. if there were 3 groups of people summarized, the table repeats the same information 3 times
Are there any common ways to address this issue? Thanks!
SELECT
Demographics.Name,
Demographics.NDoc_Number,
Demographics.PID_alphanumeric,
Demographics.Company,
Demographics.Company_Name,
Demographics.Location,
Demographics.Location_Name,
Demographics.Team_CMT,
Demographics.Case_Manager,
Demographics.Case_Manager_UID,
Demographics.SiteName,
CareEpisodes.BGNDATE,
CareEpisodes.BRFA,
CareEpisodes.ENDDATE,
CareEpisodes.ERFA,
OASIS_Improvement.BGNRPT,
OASIS_Improvement.ENDRPT,
ISNULL(SUM(CASE OASIS_Improvement.O_I_#Request.MooNum~
WHEN 'NA'
THEN 1
ELSE 0
END),0) AS numberImproveNA,
ISNULL(SUM(CASE OASIS_Stabilization.O_S_#Request.MooNum~
WHEN 'NA'
THEN 1
ELSE 0
END),0) AS numberStabilizeNA,
ISNULL(SUM(CASE OASIS_Improvement.O_I_#Request.MooNum~
WHEN 'NA'
THEN 0
ELSE 1
END),0) AS couldShowImprovement,
ISNULL(SUM(CASE OASIS_Stabilization.O_S_#Request.MooNum~
WHEN 'NA'
THEN 0
ELSE 1
END),0) AS couldShowStabilization,
ISNULL(COUNT(Demographics.Name),0) AS patientCount,
ISNULL(SUM(CASE OASIS_Improvement.O_I_#Request.MooNum~
WHEN 1
THEN 1
ELSE 0
END),0) AS doShowImprovement,
ISNULL(SUM(CASE OASIS_Stabilization.O_S_#Request.MooNum~
WHEN 1
THEN 1
ELSE 0
END),0) AS doShowStabilization
FROM
Demographics
INNER JOIN OASIS_Improvement ON
Demographics.NDoc_Number = OASIS_Improvement.NDocNumber
INNER JOIN OASIS_Stabilization ON
Demographics.NDoc_Number = OASIS_Stabilization.NDocNumber AND
OASIS_Improvement.BGNRPT=OASIS_Stabilization.BGNRPT
INNER JOIN CareEpisodes ON
Demographics.NDoc_Number = CareEpisodes.NDocNumber AND
OASIS_Improvement.BGNRPT=CareEpisodes.BGNRPT
WHERE
(Demographics.Company IN (#SingleQuote.Request.companyInput~) OR '#Request.companyInput~' = '') AND
(Demographics.Location IN (#SingleQuote.Request.locationInput~) OR '#Request.locationInput~' = '') AND
(Demographics.Team_CMT IN (#SingleQuote.Request.teamInput~) OR '#Request.teamInput~' = '') AND
(Demographics.Case_Manager_UID IN (#SingleQuote.Request.clinicianInput~) OR '#Request.clinicianInput~' = '') AND
CareEpisodes.ERFA <> 6 AND
(OASIS_Improvement.O_I_#Request.MooNum~ = 'NA' OR
OASIS_Improvement.O_I_#Request.MooNum~ = 1 OR
OASIS_Improvement.O_I_#Request.MooNum~ = 0) AND
(OASIS_Stabilization.O_S_#Request.MooNum~ = 'NA' OR
OASIS_Stabilization.O_S_#Request.MooNum~ = 0 OR
OASIS_Stabilization.O_S_#Request.MooNum~ = 1) AND
CareEpisodes.BGNDATE >= '#Request.FromDateInput~' AND
CareEpisodes.ENDDATE <= '#Request.ThruDateInput~'
You need to think about using a GROUP BY statement if you are trying to group the information. If you want to summarize the information try looking at the GROUP BY but WITH ROLLUP. ROLLUP will allow you to group and summarize information depending on the values you select in your GROUP BY.