Query takes too long if i include a column in select statement - sql

Below is the query which i need to optimize:
DECLARE #Power VARCHAR(10), #Button VARCHAR(10), #Casing VARCHAR(10), #Screen VARCHAR(10)
SELECT #Power = ActivityId FROM t_Activity WHERE ActivityName = 'PhonePowersUp?'
SELECT #Button = ActivityId FROM t_Activity WHERE ActivityName = 'T/S and Buttons functioning OK?'
SELECT #Casing = ActivityId FROM t_Activity WHERE ActivityName = 'Casing - no major defects?'
SELECT #Screen = ActivityId FROM t_Activity WHERE ActivityName = 'LCD works OK?'
SELECT
HQ.HandsetQuoteId [HandsetQuoteId], SS.Name [quote_status], HQ.QuoteDate [Quote Date], INS.DateInspected [DateInspected], PA.IMEI [IMEI_Quoted],
PA1.IMEI [IMEI_Inspected], INS.Grade [Grade], PB.PackageBoxName [PackageBoxName], CC.Name [ContactChannel], PhnBrd.Name [Brand], PM.ModelName [ModelQuoted],
PM1.ModelName [ModelInspected], U.FirstName [FirstName], U.Surname [Surname], U.Username [Username], UW.WarehouseId [WarehouseId], W.Name [Warehouse Name],
HQA.Value [Original Quote Value], HQ.QuoteValue [Quote Value], INS.InspectionValue [InspectionValue], HQ.AgreedValue [Agreed Value], CUS.FirstName [Store Name],
DATEDIFF(DAY, HQ.QuoteDate, GETDATE()) [Quote Age],
[ST_POWER] = CASE WHEN (CHARINDEX(','+ #Power +',', ','+PAR.Ok+',') > 0) THEN 'YES' WHEN (CHARINDEX(','+ #Power +',', ','+PAR.Fault+',') > 0) THEN 'NO' ELSE NULL END,
[ST_BUTTONS] = CASE WHEN (CHARINDEX(','+ #Button +',', ','+PAR.Ok+',') > 0) THEN 'YES' WHEN (CHARINDEX(','+ #Button +',', ','+PAR.Fault+',') > 0) THEN 'NO' ELSE NULL END,
[ST_CASING] = CASE WHEN (CHARINDEX(','+ #Casing +',', ','+PAR.Ok+',') > 0) THEN 'YES' WHEN (CHARINDEX(','+ #Casing +',', ','+PAR.Fault+',') > 0) THEN 'NO' ELSE NULL END,
[ST_Screen] = CASE WHEN (CHARINDEX(','+ #Screen +',', ','+PAR.Ok+',') > 0) THEN 'YES' WHEN (CHARINDEX(','+ #Screen +',', ','+PAR.Fault+',') > 0) THEN 'NO' ELSE NULL END,
st_deduct = PAR.PercentageDeduction, wt_deduct = MAX(APD.PercentageDeduction)
FROM t_Inspection AS INS
INNER JOIN t_HandsetQuote HQ ON HQ.HandsetQuoteId = INS.HandsetQuoteId
INNER JOIN t_QuoteHeader QH ON QH.QuoteHeaderId = HQ.QuoteHeaderId
INNER JOIN t_Customer CUS ON CUS.CustomerId = QH.CustomerId
INNER JOIN t_ContactChannel CC ON CC.ContactChannelId = CUS.ContactChannelId
INNER JOIN t_PackageBoxHandset PBH ON PBH.HandsetQuoteId = HQ.HandsetQuoteId
INNER JOIN t_PackageBox PB ON PB.PackageBoxId = PBH.PackageBoxId
INNER JOIN t_StockStatus SS ON SS.StockStatusId = HQ.StockStatusId
INNER JOIN t_PhoneAudit PA ON PA.PhoneAuditId = HQ.QuotePhoneAuditId
INNER JOIN t_PhoneModel PM ON PM.PhoneModelId = PA.PhoneModelId AND PA.PhoneAuditId = HQ.QuotePhoneAuditId
INNER JOIN t_PhoneBrand PhnBrd ON PM.PhoneBrandId = PhnBrd.PhoneBrandId
INNER JOIN t_PhoneAudit PA1 ON PA1.PhoneAuditId = HQ.InspectionPhoneAuditId
INNER JOIN t_PhoneModel PM1 ON PM1.PhoneModelId = PA1.PhoneModelId AND PA1.PhoneAuditId = HQ.InspectionPhoneAuditId
INNER JOIN t_PhoneBrand PhnBrd1 ON PM1.PhoneBrandId = PhnBrd1.PhoneBrandId
INNER JOIN t_User U ON INS.InspectorId = U.UserId
INNER JOIN t_UserWarehouse UW ON U.UserId = UW.UserId
INNER JOIN t_Warehouse W ON UW.WarehouseId = W.WarehouseId
LEFT JOIN t_HandsetQuoteAdditionalInfo HQA ON HQ.HandsetQuoteId = HQA.HandsetQuoteId AND HQA.KeyName = 'OriginalQuoteValue'
LEFT JOIN t_PhoneAuditRetail PAR ON PAR.HandsetQuoteId = HQ.HandsetQuoteId
LEFT JOIN t_HandsetQuoteActivity HQA1 ON HQA1.HandsetQuoteId = HQ.HandsetQuoteId AND HQA1.ActivityTestOK = 0 AND HQA1.ActivityStartTime = (
CASE
WHEN ((SELECT Count(1) FROM t_HandsetQuoteActivity WHERE HandsetQuoteId = HQA1.HandsetQuoteId AND ActivityStartTime <= QH.Cache_QuoteAcceptedDate AND ActivityId = HQA1.ActivityId) > 0)
THEN (SELECT Max(ActivityStartTime) FROM t_HandsetQuoteActivity WHERE HandsetQuoteId = HQA1.HandsetQuoteId AND ActivityStartTime <= QH.Cache_QuoteAcceptedDate AND ActivityId = HQA1.ActivityId GROUP BY HandsetQuoteId, ActivityId)
ELSE
(SELECT Min(ActivityStartTime) FROM t_HandsetQuoteActivity WHERE HandsetQuoteId = HQA1.HandsetQuoteId AND ActivityStartTime >= QH.Cache_QuoteAcceptedDate AND ActivityId = HQA1.ActivityId GROUP BY HandsetQuoteId, ActivityId)
END)
LEFT JOIN t_Activity_PercentageDeduction APD ON APD.ActivityId = HQA1.ActivityId AND APD.ContactChannelId = CUS.ContactChannelId AND APD.ContactChannelId = CC.ContactChannelId
WHERE Ins.DateInspected > GETDATE()-90
GROUP BY HQ.HandsetQuoteId, SS.Name, QH.CreatedDate, INS.DateInspected, PA.IMEI, PA1.IMEI, INS.Grade, PB.PackageBoxName, CC.Name, PhnBrd.Name, PM.ModelName, PM1.ModelName,
U.FirstName, U.Surname, U.Username, UW.WarehouseId, W.Name, HQA.Value, HQ.QuoteValue, INS.InspectionValue, HQ.AgreedValue, CUS.Firstname, HQ.QuoteDate, PAR.Ok, PAR.Fault,
PAR.PercentageDeduction
And, after properly debugging it, I came to know that when i remove wt_deduct = MAX(APD.PercentageDeduction) from the select list, the query executes with in less than a minute.
But, however i am not able to figure it out, that whats wrong with the column APD.PercentageDeduction, because when i include it in the select list, my query stucks and becomes too slow and takes 15 minutes to run and excluding it from the select list makes the query to run with in 30 seconds.
Additional Information:
Table -> t_Activity_PercentageDeduction contains only 400 records, column PercentageDeduction is of Decimal datatype.
Please let me know if you want some other information too.

If Im not mistaken you are only joining to that table in order to get that MAX value, and by adding this Max value, you are also having to do all the grouping. So there is actually quite a difference in the queries.
I would suggest using a co-related sub-query to get this piece of data.
remove the left join
LEFT JOIN t_Activity_PercentageDeduction APD ON APD.ActivityId = HQA1.ActivityId AND APD.ContactChannelId = CUS.ContactChannelId AND APD.ContactChannelId = CC.ContactChannelId
and set wt_deduct = to the new co-related sub-query
wt_deduct = (select MAX(PercentageDeduction) from t_Activity_PercentageDeduction
where ActivityId = HQA1.ActivityId
AND ContactChannelId = CUS.ContactChannelId
AND ContactChannelId = CC.ContactChannelId)
And you can remove all the grouping that is no longer required too.

Related

The SQL Server query is taking too long to load the data

The below query is actually a view which is being used to display the cash payment report. But it is taking too much of time to load the data
SELECT
Billing_AccountPaymentDate.DueDate,
SUM(Billing_AccountCharge.NetAmount) AS NetCharges,
ISNULL(SUM(AccountChargePayment.SchoolPayments + AccountChargePayment.SchoolRemittances + AccountChargePayment.SchoolRemittancesPending), 0) / SUM(Billing_AccountCharge.NetAmount) AS PercentCollected,
SUM(Billing_AccountCharge.NetAmount - ISNULL(AccountChargePayment.SchoolPayments + AccountChargePayment.SchoolRemittances + AccountChargePayment.SchoolRemittancesPending, 0)) AS RemainingBalance,
Billing_AccountPaymentDate.RemittanceEffectiveDate,
Billing_Account.SchoolId,
ISNULL(SUM(AccountChargePayment.SchoolPayments), 0) AS SchoolPayments,
ISNULL(SUM(AccountChargePayment.SchoolRemittances), 0) AS SchoolRemittances,
ISNULL(SUM(AccountChargePayment.SchoolRemittancesPending), 0) AS SchoolRemittancesPending,
Billing_Account.SchoolYearId,
ISNULL(SUM(AccountChargePayment.SchoolPayments + AccountChargePayment.SchoolRemittances), 0) AS TotalReceipts
FROM
Billing_AccountCharge
INNER JOIN
Billing_AccountInvoice ON
Billing_AccountInvoice.AccountInvoiceId = Billing_AccountCharge.AccountInvoiceId
INNER JOIN
Billing_Account ON
Billing_Account.AccountId = Billing_AccountInvoice.AccountId
INNER JOIN
Billing_PaymentMethod ON
Billing_PaymentMethod.PaymentMethodId = CASE WHEN Billing_AccountInvoice.AutomaticPaymentEligible = 1 THEN Billing_Account.PaymentMethodId ELSE 3 END -- Send Statements
INNER JOIN
Billing_AccountPaymentDate ON
Billing_AccountPaymentDate.AccountPaymentMethodId = Billing_PaymentMethod.AnticipatedAccountPaymentMethodId AND
Billing_AccountPaymentDate.DueDate = Billing_AccountInvoice.DueDate AND
Billing_AccountPaymentDate.HoldForFee = Billing_Account.HoldPaymentForFee
INNER JOIN
Billing_ChargeItem ON
Billing_ChargeItem.ChargeItemId = Billing_AccountCharge.ChargeItemId
LEFT OUTER JOIN
(
SELECT
Billing_AccountChargePayment.AccountChargeId,
SUM(CASE WHEN Billing_AccountPayment.AccountPaymentTypeId = 9 THEN Billing_AccountChargePayment.Amount ELSE 0 END) AS SchoolPayments,
SUM(CASE WHEN Billing_AccountChargePayment.SchoolRemittanceId IS NOT NULL THEN Billing_AccountChargePayment.Amount ELSE 0 END) AS SchoolRemittances,
SUM(CASE WHEN Billing_AccountChargePayment.SchoolRemittanceId IS NULL AND Billing_AccountPayment.AccountPaymentTypeId <> 9 THEN Billing_AccountChargePayment.Amount ELSE 0 END) AS SchoolRemittancesPending
FROM
Billing_AccountChargePayment
INNER JOIN
Billing_AccountPayment ON
Billing_AccountPayment.AccountPaymentId = Billing_AccountChargePayment.AccountPaymentId
GROUP BY
Billing_AccountChargePayment.AccountChargeId
) AccountChargePayment ON
AccountChargePayment.AccountChargeId = Billing_AccountCharge.AccountChargeId
WHERE
Billing_AccountInvoice.AccountInvoiceStatusId <> 4 AND -- Voided
Billing_ChargeItem.RemitToSchool = 1
AND Billing_Account.[SchoolId] = 6 --hard code in a school with data
AND Billing_Account.[SchoolYearId] = 12 --hard code in a school year with data
GROUP BY
Billing_AccountPaymentDate.DueDate,
Billing_AccountPaymentDate.RemittanceEffectiveDate,
Billing_Account.SchoolId,
Billing_Account.SchoolYearId
HAVING
SUM(Billing_AccountCharge.NetAmount) <> 0
order by Billing_AccountPaymentDate.DueDate ASC
It looks like the inner query in the left join is taking too much of time, both the tables already have non clustered index, I tried taking those tables outside but the data is not accurate
Use CTE instead of subquery and do all calculation there instead of in Left outer join. Moreover, use with(nolock) whenever you fetch data. Still your query is taking much more time then You should implement proper indexing.
WITH PaymentData AS (
SELECT
acp.AccountChargeId,
SUM(
CASE
WHEN ap.AccountPaymentTypeId = 9 THEN acp.Amount
ELSE 0
END
) AS SchoolPayments,
SUM(
CASE
WHEN acp.SchoolRemittanceId IS NOT NULL THEN acp.Amount
ELSE 0
END
) AS SchoolRemittances,
SUM(
CASE
WHEN acp.SchoolRemittanceId IS NULL AND ap.AccountPaymentTypeId <> 9 THEN acp.Amount
ELSE 0
END
) AS SchoolRemittancesPending
FROM
Billing_AccountChargePayment acp WITH(NOLOCK)
INNER JOIN Billing_AccountPayment ap WITH(NOLOCK) ON acp.AccountPaymentId = ap.AccountPaymentId
GROUP BY
acp.AccountChargeId
)
SELECT
apd.DueDate,
SUM(ac.NetAmount) AS NetCharges,
COALESCE(
SUM(pd.SchoolPayments + pd.SchoolRemittances + pd.SchoolRemittancesPending),
0
) / SUM(ac.NetAmount) AS PercentCollected,
SUM(ac.NetAmount - COALESCE(pd.SchoolPayments, 0) - COALESCE(pd.SchoolRemittances, 0) - COALESCE(pd.SchoolRemittancesPending, 0)) AS RemainingBalance,
apd.RemittanceEffectiveDate,
a.SchoolId,
COALESCE(SUM(pd.SchoolPayments), 0) AS SchoolPayments,
COALESCE(SUM(pd.SchoolRemittances), 0) AS SchoolRemittances,
COALESCE(SUM(pd.SchoolRemittancesPending), 0) AS SchoolRemittancesPending,
a.SchoolYearId,
COALESCE(SUM(pd.SchoolPayments + pd.SchoolRemittances), 0) AS TotalReceipts
FROM
Billing_AccountCharge ac WITH(NOLOCK)
INNER JOIN Billing_AccountInvoice ai WITH(NOLOCK) ON ac.AccountInvoiceId = ai.AccountInvoiceId
INNER JOIN Billing_Account a WITH(NOLOCK) ON ai.AccountId = a.AccountId
INNER JOIN Billing_PaymentMethod pm WITH(NOLOCK) ON pm.PaymentMethodId = CASE
WHEN ai.AutomaticPaymentEligible = 1 THEN a.PaymentMethodId
ELSE 3
END
INNER JOIN Billing_AccountPaymentDate apd WITH(NOLOCK) ON
apd.AccountPaymentMethodId = pm.AnticipatedAccountPaymentMethodId AND
apd.DueDate = ai.DueDate AND
apd.HoldForFee = a.HoldPaymentForFee
INNER JOIN Billing_ChargeItem ci WITH(NOLOCK) ON ac.ChargeItemId = ci.ChargeItemId
LEFT OUTER JOIN PaymentData pd WITH(NOLOCK) ON ac.AccountChargeId = pd.AccountChargeId
WHERE
ai.AccountInvoiceStatusId <> 4 AND
ci.RemitToSchool = 1 AND
a.SchoolId = 6 AND
a.SchoolYearId = 12
GROUP BY
apd.DueDate,
apd.RemittanceEffectiveDate,
a.SchoolId,
a.SchoolYearId
HAVING
SUM(ac.NetAmount) <> 0
ORDER BY
apd.DueDate ASC;

Unexplainable SQL behaviour

I have a simple SQL query, with a handful of joined queries.
In my select I have a function shaping the date to a string format as below
LEFT(REPLACE(ADM_DT,'-',''),8)+REPLACE(ADM_TM,':','')+'00'
The script I am running should return 84 rows currently, but when executing the above in the select, it continuosly returns a different volume of rows every execution? there are no changes to the underlying tables between executions.
The strange thing is that whe I swith this back to a standard date conversion, the rows total 84
CONVERT(DATETIME,CONVERT(NVARCHAR,ADM_DT)+' '+ADM_TM)
Can anyone explain why SQL is behaving this way, I have not seen this before?
Full script below:
SELECT
[Visit ID] = a050.HSP_NO
,[Current Site] = currwd.HOSP
,[Current Specialty] = curr.SPEC
,[Current Ward] = currwd.WARD
,[Current Ward Name] = REPLACE(currwd.CURRDESC,'"','')
,[Current Consultant] = curr.PROF
,[Admission Date] = LEFT(REPLACE(ADM_DT,'-',''),8)+REPLACE(ADM_TM,':','')+'00'
,[Active] = '1'
,[PAS ID] = [crn].[crn]
,[Patient Class] = 'IP'
,NHS.[nhsno]
,CHI.CHI
,CASE WHEN OSV.X_CN IS NOT NULL THEN 'OSV' ELSE '' END OSV
,CASE WHEN NHS.[nhsno] LIKE '7%' THEN '7 NHSNO' ELSE '' END [PROBLEM NHS NO]
,DATEDIFF(D,PATS.DATE_OF_BIRTH,CONVERT(DATE,ADM_DT)) /365 [AGE ON ADMISSION]
FROM PCSSSA..SILVER.APK050_HPROVSPELL a050 WITH (NOLOCK)
-- Current Admission details
LEFT JOIN (
SELECT X_CN, CEP_NO, HSP_NO, SPEC, PROF --MSPEC
FROM PCSSSA..SILVER.APK051_CONEPIS epi WITH (NOLOCK)
-- Main Specialty Map
LEFT JOIN PCSSSA..SILVER.ENV050_DISCIPDETS en050 WITH (NOLOCK)
ON epi.SPEC = en050.OBJ_DISC
AND en050.OBJ_TYPE='SP'
AND en050.DATE_TO IS NULL
)curr
ON curr.X_CN = a050.X_CN
AND a050.HSP_NO = curr.HSP_NO
AND curr.CEP_NO = (SELECT TOP 1 a051.CEP_NO
FROM PCSSSA..SILVER.APK051_CONEPIS a051 WITH (NOLOCK)
Where a051.X_CN = a050.X_CN AND a050.HSP_NO = a051.HSP_NO
Order By CEP_NO DESC)
-- Current Ward Detail
JOIN (SELECT *, ROW_NUMBER() OVER (PARTITION BY X_CN, CEP_NO ORDER BY WS_NO DESC) AS WR
FROM PCSSSA..SILVER.APK052_WARDSTAY wdstay WITH (NOLOCK)
LEFT JOIN (SELECT
CURRWARD = OBJ_LOC,
CURRDESC = OBJ_DESC
FROM [PCSSSA]..[SILVER].[ENV030_LOCDETS] WITH (NOLOCK)
WHERE OBJ_TYPE = 'WARD'
AND DATE_TO IS NULL
)wdname
ON wdstay.WARD = wdname.CURRWARD
) currwd
ON curr.X_CN = currwd.X_CN
AND curr.CEP_NO = currwd.CEP_NO
AND currwd.WR=1
--- Admitting details
LEFT JOIN (
SELECT X_CN, CEP_NO, HSP_NO, PROF, SPEC --MSPEC
FROM PCSSSA..SILVER.APK051_CONEPIS epi WITH (NOLOCK)
-- Main Specialty Map
LEFT JOIN PCSSSA..SILVER.ENV050_DISCIPDETS en050 WITH (NOLOCK)
ON epi.SPEC = en050.OBJ_DISC
AND en050.OBJ_TYPE='SP'
AND en050.DATE_TO IS NULL
)adm
ON adm.X_CN = a050.X_CN AND a050.HSP_NO = adm.HSP_NO
AND adm.CEP_NO = (SELECT TOP 1 a051.CEP_NO
FROM PCSSSA..SILVER.APK051_CONEPIS a051 WITH (NOLOCK)
Where a051.X_CN = a050.X_CN AND a050.HSP_NO = a051.HSP_NO
Order By CEP_NO)
-- Admitting Ward Detail
JOIN (SELECT *, ROW_NUMBER() OVER (PARTITION BY X_CN,CEP_NO ORDER BY WS_NO) AS WR FROM PCSSSA..SILVER.APK052_WARDSTAY WITH (NOLOCK)) admwd
ON adm.X_CN = admwd.X_CN
AND adm.CEP_NO = admwd.CEP_NO
AND admwd.WR=1
-- Patient Detail
LEFT JOIN
(SELECT
[id].[RM_PATIENT_NO],
[id].[NUM_ID_TYPE] + CONVERT(NVARCHAR,[NUMBER_ID]) [crn]
FROM [PCSSSA]..[SILVER].[NUMBER_IDS] [id] WITH (NOLOCK)
WHERE [id].[NUM_ID_TYPE] IN ('0', '1', 'W')
)[crn]
ON a050.[X_CN] = [crn].[RM_PATIENT_NO]
-- NHS NUMBERS
LEFT JOIN
(
SELECT
[id].[RM_PATIENT_NO],
[id].[NUMBER_ID] [nhsno]
FROM [PCSSSA]..[SILVER].[NUMBER_IDS] [id] WITH (NOLOCK)
WHERE [id].[NUM_ID_TYPE] = ('NHS')
)NHS
ON NHS.RM_PATIENT_NO = a050.X_CN
-- CHI NUMBER
LEFT JOIN
(
SELECT
[id].[RM_PATIENT_NO],
[id].[NUMBER_ID] [CHI]
FROM [PCSSSA]..[SILVER].[NUMBER_IDS] [id] WITH (NOLOCK)
WHERE [id].[NUM_ID_TYPE] IN ('CHI')
)CHI
ON CHI.RM_PATIENT_NO = a050.X_CN
-- OVERSEES STATUS
LEFT JOIN
(
SELECT X_CN, [STATUS], SDATE, EDATE FROM PCSSSA..SILVER.CRS037_OSV_STATUS WITH (NOLOCK)
)OSV
ON OSV.X_CN = a050.X_CN
AND CONVERT(DATE,ADM_DT) >= OSV.SDATE
AND (OSV.SDATE IS NULL
OR CONVERT(DATE,ADM_DT) <= OSV.EDATE)
-- DEMOGRAPHICS
LEFT JOIN
(
SELECT RM_PATIENT_NO, DATE_OF_BIRTH FROM PCSSSA..[SILVER].[PATIENTS] WITH (NOLOCK)
)PATS
ON PATS.RM_PATIENT_NO = a050.X_CN
-- CURRENTLY ADMITTED ONLY
WHERE DIS_DT IS NULL
-- WITHOUT NHS NUMBER
AND (nhsno IS NULL
-- OR BRING IN ANY 7 NHS NUMBERS FOR CORRECTION
OR NHS.[nhsno] LIKE '7%'
-- ALSO INCLUDE OVERSEES
OR OSV.X_CN IS NOT NULL)
What is even stranger, is that if you wrap this in a subquery and coun(*) on the outer then it totals 84 as expected, very strange!

Else if in my select statement

I want to have an else if in my select statement i have already tried using case when but the results are not so accurate
heres a snippet of my scripts
select distinct t.MovementDate, t.ContractMovementID, t.GID,t.ReferenceGID,
p.refno, t.amount,convert(date,t.CreatedDate) as createdDat
from
LIF_MGM_T_Contract p
inner join LIF_MMS_T_PolicySuspense s with (nolock)
on s.ContractGID = p.GID
inner join LIF_TMS_T_FinancialTransaction t with (nolock)
on t.ContractGID = p.GID
where
p.refno = '1030642 - 1 - Mohahlaula'
and t.ReversedIndicator = 1
and t.counter = (select min(counter)
from LIF_TMS_T_FinancialTransaction t2 with (nolock)
where t2.ContractGID = p.GID
and t2.ReversedIndicator = 1
and t2.MovementDate = t.MovementDate )
So i want a else if t2.reversedindicator = 0 and date = getdate() return results.. Hope this makes sense

Summing two seperate queries into one value using UNION ALL clause

I have the following query (as part of a larger query). I am trying to get the sum results from 2 different data sets within a subquery but I am having trouble trying to encapsulate the two into 1 value. What I have is this:
(Select SUM('Invoiced MTD') from
((Select SUM(CASE WHEN SOH.LASDLVNUM_0 <> '' AND SOH.LASINVNUM_0 <> '' AND MONTH(SOH.SHIDAT_0) = MONTH(GETDATE()) THEN
(SOP.NETPRI_0 * SOQ.QTY_0 * SOH.CHGRAT_0) ELSE 0 END) as 'Invoiced MTD'
From x3v6.CICPROD.SORDER SOH
LEFT OUTER JOIN x3v6.CICPROD.BPCUSTOMER BPC on SOH.BPCORD_0 = BPC.BPCNUM_0
LEFT OUTER JOIN x3v6.CICPROD.SORDERQ SOQ on SOH.SOHNUM_0 = SOQ.SOHNUM_0
LEFT OUTER JOIN x3v6.CICPROD.SORDERP SOP on SOQ.SOHNUM_0 = SOP.SOHNUM_0 and SOQ.SOPLIN_0 = SOP.SOPLIN_0 and SOQ.SOQSEQ_0 = SOP.SOPSEQ_0
LEFT OUTER JOIN x3v6.CICPROD.ITMMASTER ITM on SOP.ITMREF_0 = ITM.ITMREF_0 ))
UNION ALL
((Select SUM(CASE WHEN SIH.INVTYP_0 = 2 and MONTH(SIH.ACCDAT_0) = MONTH(GETDATE()) THEN SID.AMTNOTLIN_0 * (-1) ELSE 0 END) as 'Invoiced MTD'
From x3v6.CICPROD.SINVOICE SIH
Left Outer Join x3v6.CICPROD.SINVOICED SID on SIH.NUM_0 = SID.NUM_0))
as 'T2',
But I am getting an error where the UNION ALL clauses is, and I can't figure it out. Basically I want to combine Sales credit memos with the sales order dollar totals from a seperate table.
Can anyone assist me with this?
What about this ?
Select SUM([Invoiced MTD]) from
(
Select SUM(CASE WHEN SOH.LASDLVNUM_0 <> '' AND SOH.LASINVNUM_0 <> '' AND MONTH(SOH.SHIDAT_0) = MONTH(GETDATE())
THEN (SOP.NETPRI_0 * SOQ.QTY_0 * SOH.CHGRAT_0) ELSE 0 END) as 'Invoiced MTD'
From x3v6.CICPROD.SORDER SOH
LEFT OUTER JOIN x3v6.CICPROD.BPCUSTOMER BPC on SOH.BPCORD_0 = BPC.BPCNUM_0
LEFT OUTER JOIN x3v6.CICPROD.SORDERQ SOQ on SOH.SOHNUM_0 = SOQ.SOHNUM_0
LEFT OUTER JOIN x3v6.CICPROD.SORDERP SOP on SOQ.SOHNUM_0 = SOP.SOHNUM_0 and SOQ.SOPLIN_0 = SOP.SOPLIN_0 and SOQ.SOQSEQ_0 = SOP.SOPSEQ_0
LEFT OUTER JOIN x3v6.CICPROD.ITMMASTER ITM on SOP.ITMREF_0 = ITM.ITMREF_0
UNION ALL
Select SUM(CASE WHEN SIH.INVTYP_0 = 2 and MONTH(SIH.ACCDAT_0) = MONTH(GETDATE())
THEN SID.AMTNOTLIN_0 * (-1) ELSE 0 END) as 'Invoiced MTD'
From x3v6.CICPROD.SINVOICE SIH
Left Outer Join x3v6.CICPROD.SINVOICED SID on SIH.NUM_0 = SID.NUM_0
)T
Does this work? I'm not sure exactly what is causing your issue, but you definitely don't need so many parenthesis. I would also recommend using something that formats/ beautifies your SQL. It's a great way to 1) keep your code looking consistent and 2) flesh out syntax errors.
SELECT SUM(x.invoiced_mtd)
FROM (SELECT SUM(CASE
WHEN soh.lasdlvnum_0 <> '' AND soh.lasinvnum_0 <> '' AND
MONTH(soh.shidat_0) = MONTH(getdate()) THEN
(sop.netpri_0 * soq.qty_0 * soh.chgrat_0)
ELSE
0
END) AS invoiced_mtd
FROM x3v6.cicprod.sorder soh
LEFT OUTER JOIN x3v6.cicprod.bpcustomer bpc
ON soh.bpcord_0 = bpc.bpcnum_0
LEFT OUTER JOIN x3v6.cicprod.sorderq soq
ON soh.sohnum_0 = soq.sohnum_0
LEFT OUTER JOIN x3v6.cicprod.sorderp sop
ON soq.sohnum_0 = sop.sohnum_0
AND soq.soplin_0 = sop.soplin_0
AND soq.soqseq_0 = sop.sopseq_0
LEFT OUTER JOIN x3v6.cicprod.itmmaster itm
ON sop.itmref_0 = itm.itmref_0
UNION ALL
SELECT SUM(CASE
WHEN sih.invtyp_0 = 2 AND
MONTH(sih.accdat_0) = MONTH(getdate()) THEN
sid.amtnotlin_0 * (-1)
ELSE
0
END)
FROM x3v6.cicprod.sinvoice sih
LEFT OUTER JOIN x3v6.cicprod.sinvoiced sid
ON sih.num_0 = sid.num_0) x;
Try using a CTE for the UNION query first. Here is a simplified example with the same structure as your query:
;with cteTest AS (
((select 2 as 'test'))
union all
((select 3 as 'test'))
)
select sum(test) from cteTest

SQL Pivot table for Blank data

following is my Query to generate the Pivoted result:
SELECT '# of Corrective Actions open and overdue' as [Corrective Actions breakdown],
[405],
[2865],
[3142],
[405]+[2865]+[3142] as [Total]
FROM
(Select il.Locationid , ca.CorrectiveActionsid, il.locOrder, ca.isDeleted caDeleted, i.isDeleted iDeleted, i.CompanyId companyid,ca.CADateBy, ca.Status from IncidentLocation il inner join incident i on il.IncidentId = i.IncidentId
inner join CorrectiveActions ca on i.IncidentId = ca.IncidentId
) AS SourceTable
PIVOT
(
COUNT(CorrectiveActionsid)
FOR LocationId IN ([405],[2865],[3142])
) PivotTable
where locOrder = 0 and caDeleted =0 and iDeleted = 0 and companyId = 210
and CADateBy <= '2013-01-01' and [Status] = 'Open'
I was thinking for blank data the count should return o. But I am getting no result at all. Please guide me what wrong I am doing and what should I do to get zero instead of blank for all the counted values.
looks like your query doesn't return any row, you can fix it like this (I've not fixed other parts of query, just want to show you a workaround):
select
A.[Corrective Actions breakdown],
coalesce([405], 0) as [405],
coalesce([2865], 0) as [2865],
coalesce([3142], 0) as [3142],
coalesce([405], 0) + coalesce([2865], 0) + coalesce([3142], 0) as [Total]
from (select '# of Corrective Actions open and overdue' as [Corrective Actions breakdown]) as A
outer apply (
SELECT
[405],
[2865],
[3142]
FROM
(Select il.Locationid , ISNULL(ca.CorrectiveActionsid, 0) AS CorrectiveActionsid, il.locOrder, ca.isDeleted caDeleted, i.isDeleted iDeleted, i.CompanyId companyid,ca.CADateBy, ca.Status from IncidentLocation il inner join incident i on il.IncidentId = i.IncidentId
inner join CorrectiveActions ca on i.IncidentId = ca.IncidentId
) AS SourceTable
PIVOT
(
COUNT(CorrectiveActionsid)
FOR LocationId IN ([405],[2865],[3142])
) PivotTable
where locOrder = 0 and caDeleted =0 and iDeleted = 0 and companyId = 210
and CADateBy <= '2013-01-01' and [Status] = 'Open'
) as p
I would expect the count() to return 0. If it doesn't, you can try using coalesce():
coalesce([405], 0) as [405]
In SQL Server COUNT will ignore NULL values. That being said, use an ISNULL function on the column you are going to aggregate.
SELECT '# of Corrective Actions open and overdue' as [Corrective Actions breakdown],
[405],
[2865],
[3142],
[405]+[2865]+[3142] as [Total]
FROM
(Select il.Locationid , ISNULL(ca.CorrectiveActionsid, 0) AS CorrectiveActionsid, il.locOrder, ca.isDeleted caDeleted, i.isDeleted iDeleted, i.CompanyId companyid,ca.CADateBy, ca.Status from IncidentLocation il inner join incident i on il.IncidentId = i.IncidentId
inner join CorrectiveActions ca on i.IncidentId = ca.IncidentId
) AS SourceTable
PIVOT
(
COUNT(CorrectiveActionsid)
FOR LocationId IN ([405],[2865],[3142])
) PivotTable
where locOrder = 0 and caDeleted =0 and iDeleted = 0 and companyId = 210
and CADateBy <= '2013-01-01' and [Status] = 'Open'