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 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.
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().
--I am trying to simply add one subquery to take the total sales of each salesperson in relation to their quotes. I am at a loss and hopefully someone can help.
select sp.FIRST_NAME + ' ' + sp.LAST_NAME,
sum(case when sq.SAL_QUOTE_STATUS_ID = '1' then 1 else 0 end) as [Created],
sum(case when sq.SAL_QUOTE_STATUS_ID = '4' then 1 else 0 end) as [Ordered],
sum(case when sq.SAL_QUOTE_STATUS_ID = '3' then 1 else 0 end) as [Rejected],
sum(sq.AMOUNT_INCLUDING_TAX) as [Amount],
sum(sq.COST) as [Cost],
sum(sq.AMOUNT_INCLUDING_TAX - sq.COST) as [Profit],
round(100 * (case when sum(sq.AMOUNT_INCLUDING_TAX) > 0 then
(sum(sq.AMOUNT_INCLUDING_TAX) -
sum(sq.COST)) / sum(sq.AMOUNT_INCLUDING_TAX) else 0 end), 3) as [GP%],
(Select sum(so.amount_including_tax)
from SAL_SALES_ORDER so
where so.SALESPERSON_ID = sp.SALESPERSON_ID) as [YTD Sales]
from SAL_SALES_QUOTE sq
inner join CRM_SALESPERSON sp on sp.SALESPERSON_ID = sq.SALESPERSON_ID
where sq.CREATED_DATE > '01-01-2018'
group by sp.FIRST_NAME + ' ' + sp.LAST_NAME
I took your subquery out of the select, made it into a result set to join on , and then pulled the sum from there.
select sp.FIRST_NAME + ' ' + sp.LAST_NAME,
sum(case when sq.SAL_QUOTE_STATUS_ID = '1' then 1 else 0 end) as [Created],
sum(case when sq.SAL_QUOTE_STATUS_ID = '4' then 1 else 0 end) as [Ordered],
sum(case when sq.SAL_QUOTE_STATUS_ID = '3' then 1 else 0 end) as [Rejected],
sum(sq.AMOUNT_INCLUDING_TAX) as [Amount],
sum(sq.COST) as [Cost],
sum(sq.AMOUNT_INCLUDING_TAX - sq.COST) as [Profit],
round(100 * (case when sum(sq.AMOUNT_INCLUDING_TAX) > 0 then
(sum(sq.AMOUNT_INCLUDING_TAX) -
sum(sq.COST)) / sum(sq.AMOUNT_INCLUDING_TAX) else 0 end), 3) as [GP%],
sum([x.ytd_sales]) AS YTD_Sales
from SAL_SALES_QUOTE sq
inner join CRM_SALESPERSON sp on sp.SALESPERSON_ID = sq.SALESPERSON_ID
inner join (Select so.salesperson_id, sum(so.amount_including_tax) AS [YTD Sales]
from SAL_SALES_ORDER so
group by so.salesperson_id) x
ON x.salesperson_id = sp.salesperson_id
where sq.CREATED_DATE > '01-01-2018'
group by sp.FIRST_NAME + ' ' + sp.LAST_NAME
I'm developping a tool which generates an excel table with SQL results.
I have several days, several payment methods (fe: credit card, check, species) and several sums.
I am doing this request :
SELECT TE.DATE AS 'JOUR', SUM(TE.TOTAL_TTC) AS 'CA TTC', ME.LIBELLE AS 'LIBELLE'
FROM TICKET TE
INNER JOIN MODE_REGLEMENT ME ON ME.CODE = TE.MODE_REGLEMENT
GROUP BY TE.DATE, ME.LIBELLE
(MODE_REGLEMENT means payment method)
And i have this result :
**JOUR** **CA TTC** **LIBELLE**
07/03/2014 1409.66 CREDIT CARD
07/03/2014 70 CHECK
07/03/2014 1393.31 SPECIES
08/03/2014 3368.07 CREDIT CARD
08/03/2014 599.44 SPECIES
09/03/2014 268.7 CREDIT CARD
09/03/2014 174.62 CHECK
But i'm searching to generate something like that :
**JOUR** **CA TTC** **CREDIT CARD** **CHECK** **SPECIES**
07/03/2014 2872.97 1409.66 70 1393.31
08/03/2014 3967.51 3368.07 0 599.44
09/03/2014 443.32 268.7 174.62 0
The column 'CA TTC' will be the sum of each payment methods.
Can you please help me to do a request (for SQL Server) to have the result i want.
Thank you a lot !
(sorry for the bad english i'm french)
You need to use PIVOT
Find the total per JOUR using SUM over() in pivot source query.
SELECT jour,
CA_TTC=total,
[CREDIT CARD]=Isnull([CREDIT CARD], 0),
[CHECK]=Isnull([CHECK], 0),
[SPECIES]=Isnull([SPECIES], 0)
FROM (SELECT *,
Sum(CA_TTC)OVER(partition BY JOUR) total
FROM Your_result) a
PIVOT (Max(CA_TTC)
FOR LIBELLE IN([CREDIT CARD],
[CHECK],
[SPECIES])) pv
SQLFIDDLE DEMO
Another method is to use conditional aggregation or SUM(CASE WHEN ... END):
;WITH CTE([JOUR], [CA TTC], [LIBELLE]) AS(
SELECT
TE.DATE AS 'JOUR',
SUM(TE.TOTAL_TTC) AS 'CA TTC',
ME.LIBELLE AS 'LIBELLE'
FROM TICKET TE
INNER JOIN MODE_REGLEMENT ME ON ME.CODE = TE.MODE_REGLEMENT
GROUP BY TE.DATE, ME.LIBELLE
)
SELECT
[JOUR],
[CA TTC] =
SUM(CASE WHEN [LIBELLE] = 'CREDIT CARD' THEN [CA TTC] ELSE 0 END) +
SUM(CASE WHEN [LIBELLE] = 'CHECK' THEN [CA TTC] ELSE 0 END) +
SUM(CASE WHEN [LIBELLE] = 'SPECIES' THEN [CA TTC] ELSE 0 END),
[CREDIT CARD] = SUM(CASE WHEN [LIBELLE] = 'CREDIT CARD' THEN [CA TTC] ELSE 0 END),
[CHECK] = SUM(CASE WHEN [LIBELLE] = 'CHECK' THEN [CA TTC] ELSE 0 END),
[SPECIES] = SUM(CASE WHEN [LIBELLE] = 'SPECIES' THEN [CA TTC] ELSE 0 END)
FROM CTE
GROUP BY [JOUR]