Incorrect syntax near the keyword 'OVER' - sql-server-2005

When attempting to calculate an expression, I get the error Incorrect syntax near the keyword 'OVER'.
I'm not sure what is the error on this line:
(SUM([DCT].[Quantity_Stk] * [ICP].[UnitCost] )) - ((#PurchaseCost + #Prod_CostLBS ) * #InputWeight ) OVER (PARTITION BY [ARC].[CustomerCode] )
I was able to use OVER on another expression and it worked just fine and was formatted like the one above, except it was only taking the SUM of one column.
Full Code:
SET NOCOUNT ON;
DECLARE #PurchaseCost Decimal(19,8);
DECLARE #InputWeight Decimal(19,8);
DECLARE #Prod_CostLBS Decimal(19,8);
SET #PurchaseCost = 2.58;
SET #InputWeight = 18100;
SET #Prod_CostLBS = .15;
SELECT
CAST([ARC].[CustomerCode] AS NVARCHAR(40)) + ' - ' + CAST([ARC].[Name] AS NVARCHAR(40)) AS [Supplier]
, [PC].ProductCode
, [PC].Description1
, Count(IC_ProductLots.OriginalQuantity_Alt) AS [Boxes]
, IC_ProductLots.UnitOfMeasure_Alt
, Sum(IC_ProductLots.OriginalQuantity_Stk) AS [Weight]
, IC_ProductLots.UnitOfMeasure_Stk
, [ICP].UnitCost AS [Unit Cost]
, Sum([DCT].[Quantity_Stk] *[ICP].[UnitCost]) AS [Total Sales]
, Avg(([IC_ProductLots].[OriginalQuantity_Stk] / [IC_ProductLots].[OriginalQuantity_Alt])) AS [Avg. Box Weight]
, Sum([IC_ProductLots].[OriginalQuantity_Stk] / #InputWeight) AS [Yield]
, CAST (#InputWeight - SUM(Sum([IC_ProductLots].[OriginalQuantity_Stk])) OVER () AS DECIMAL(18,2)) AS [Shrink]
, Max(CAST ((#PurchaseCost + #Prod_CostLBS) * #InputWeight AS DECIMAL (18,2))) AS [Cost]
, SUM([DCT].[Quantity_Stk] * [ICP].[UnitCost]) - ((#PurchaseCost + #Prod_CostLBS) * #InputWeight) OVER (PARTITION BY [ARC].[CustomerCode])
AS [Profit]
FROM (((( IC_Products [PC]
INNER JOIN DC_Transactions [DCT]
ON [PC].ProductKey = [DCT].ProductKey)
INNER JOIN AR_Customers [ARC]
ON [DCT].CustomerKey = [ARC].CustomerKey)
INNER JOIN IC_ProductLots
ON [DCT].LotKey = IC_ProductLots.LotKey)
LEFT OUTER JOIN IC_ProductCosts [ICP]
ON ICP.ProductKey=PC.ProductKey and ICP.ProductCostCode=5)
WHERE
(IC_ProductLots.ProductionDate >= { ts '2015-06-24 00:00:00' } AND (IC_ProductLots.ProductionDate <= { ts '2015-06-24 00:00:00' } OR IC_ProductLots.ProductionDate Is Null))
AND ((1=1) AND [ARC].CustomerKey IN (124) )
GROUP BY
CAST([ARC].[CustomerCode] AS NVARCHAR(40)) + ' - ' + CAST([ARC].[Name] AS NVARCHAR(40))
, [PC].ProductCode
, [PC].Description1
, IC_ProductLots.UnitOfMeasure_Alt
, IC_ProductLots.UnitOfMeasure_Stk
, [ICP].UnitCost
, IC_ProductLots.ProductionDate
, [ARC].CustomerKey
ORDER BY
CAST([ARC].[CustomerCode] AS NVARCHAR(40)) + ' - ' + CAST([ARC].[Name] AS NVARCHAR(40))
, CAST (#InputWeight - SUM(Sum([IC_ProductLots].[OriginalQuantity_Stk])) OVER () AS DECIMAL(18,2))
, Max(CAST ((#PurchaseCost + #Prod_CostLBS) * #InputWeight AS DECIMAL (18,2)))
I am using Microsoft SQL Server 2005.
Example Data for:
SUM([DCT].[Quantity_Stk] * [ICP].[UnitCost]
- ( ( #PurchaseCost + #Prod_CostLBS ) * #InputWeight ))
OVER (PARTITION BY [ARC].[CustomerCode]) AS [Profit]
DCT.Quanity_Stk = 25
ICP.UnitCost = 3.50
PurchaseCost = 2.50
Prod_CostLBS = .50
InputWeight = 30
(25 * 3.50) - ((2.50 + .50) * 30) = -2.5
87.5 - (3 * 30) = -2.5
87.5 - 90 = -2.5

SUM([DCT].[Quantity_Stk] * [ICP].[UnitCost])
- ((#PurchaseCost + #Prod_CostLBS) * #InputWeight)
OVER (PARTITION BY [ARC].[CustomerCode]) AS [Profit]
Is not correct syntax.
You can't stick arbitrary expressions between the aggregate and the over
Presumably you need
SUM([DCT].[Quantity_Stk] * [ICP].[UnitCost])
OVER (PARTITION BY [ARC].[CustomerCode])
- ( ( #PurchaseCost + #Prod_CostLBS ) * #InputWeight ) AS [Profit]
If you are trying to adjust the result after the SUM.
Or
SUM([DCT].[Quantity_Stk] * [ICP].[UnitCost]
- ( ( #PurchaseCost + #Prod_CostLBS ) * #InputWeight ))
OVER (PARTITION BY [ARC].[CustomerCode]) AS [Profit]
if you are trying to adjust the values that get summed.

Related

When make concatenation sql string query , error has occurred because single quote

SET #InventoryQuery = N'SELECT * FROM
(
SELECT Inven.Inventory_ID As ID,Inven.Inventory_ID As Number, Inventory_Date As ActionDate, ''Inventory'' AS [ActionType], IsNull(Sum(Product_Qty),0) Product_Qty, P.Product_Desc_ENG + '' ('' + P.Product_Weight + '')'' Product_Desc_ENG
FROM CRM.Product P
INNER JOIN [crm].[InventoryDetail] InvenDet ON P.Product_ID = InvenDet.Product_ID
INNER JOIN [crm].[Inventory] Inven ON Inven.Inventory_ID = InvenDet.Inventory_ID
WHERE Inven.Customer_Id = ' + CAST(#CustomerID AS VARCHAR(10)) +
' AND ( Inven.Inventory_Date BETWEEN ' + CONVERT(VARCHAR(20), #StartDate, 121) + '
AND ' + CONVERT(VARCHAR(20), #EndDate, 121) + ' ) GROUP BY Inven.Inventory_ID, Inventory_Date,P.Product_Desc_ENG,P.Product_Weight
) y
pivot
(
sum(Product_Qty)
for Product_Desc_ENG in (' + #cols + N')
) p2 '

Self Join Issue - Defining Extracted Time Periods

In the below query, I extract the month in the Select query. I then execute multiple Self Joins using the extracted month. I am getting an
Invalid column name 'mnth'
for every time that field is referenced in the Self Joins. Where would I define the extracted month in the query below?
SELECT MONTH(frcst.InvDate) AS mnth
, frcst.LineCode
, frcst.ClassCode
, cc_type
, rank
, keycust1
, keycust2
, keycust3
, sales1
, sales2
, sales3
, SUM(ship2017.GrossSales) AS gross_sales2017
, SUM(ship2017.QtyShip + ( (ship2017.QtyOrd - ship2017.QtyShip) * 0.25) ) AS frcst_qty2017
, SUM(ship2018.GrossSales) AS gross_sales2018
, SUM(ship2018.QtyShip + ( (ship2018.QtyOrd - ship2018.QtyShip) * 0.25) ) AS frcst_qty2018
, SUM(ship2019.GrossSales) AS gross_sales2019
, SUM(ship2019.QtyShip + ( (ship2019.QtyOrd - ship2019.QtyShip) * 0.25) ) AS frcst_qty2019
, SUM(ship2020.GrossSales) AS gross_sales2020
, SUM(ship2020.QtyShip + ( (ship2020.QtyOrd - ship2017.QtyShip) * 0.25) ) AS frcst_qty2020
FROM FrcstFactTbl frcst
JOIN account_hierarchy_lu account
ON frcst.AccountNumber = account.account_number
JOIN cc_type_lu cct
ON frcst.ClassCode = cct.class_code
JOIN pop_code_lu pop
ON frcst.PartNumber = pop.PartNumber
JOIN FrcstFactTbl ship2017
ON frcst.mnth = ship2017.mnth
AND frcst.LineCode = ship2017.LineCode
AND frcst.ClassCode = ship2017.ClassCode
AND frcst.AccountNumber = ship2017.AccountNumber
JOIN FrcstFactTbl ship2018
ON frcst.mnth = ship2018.mnth
AND frcst.LineCode = ship2018.LineCode
AND frcst.ClassCode = ship2018.ClassCode
AND frcst.AccountNumber = ship2018.AccountNumber
JOIN FrcstFactTbl ship2019
ON frcst.mnth = ship2019.mnth
AND frcst.LineCode = ship2019.LineCode
AND frcst.ClassCode = ship2019.ClassCode
AND frcst.AccountNumber = ship2019.AccountNumber
JOIN FrcstFactTbl ship2020
ON frcst.mnth = ship2020.mnth
AND frcst.LineCode = ship2020.LineCode
AND frcst.ClassCode = ship2020.ClassCode
AND frcst.AccountNumber = ship2019.AccountNumber
WHERE YEAR(ship2017.InvDate) = '2017'
AND YEAR(ship2018.InvDate) = '2018'
AND YEAR(ship2019.InvDate) = '2019'
AND YEAR(ship2020.InvDate) = '2020'
GROUP BY mnth, frcst.LineCode, frcst.ClassCode, cc_type, rank, keycust1, keycust2, keycust3, sales1, sales2, sales3
ORDER BY mnth
The only place you can use a column alias (which is what mnth is) is in the order by clause. Everywhere else you have to use the computation MONTH(frcst.InvDate) or else compute it in a sub-query.
I would use a sub-query i.e. replace this line:
FROM FrcstFactTbl frcst
With this:
FROM (
select *, MONTH(frcst.InvDate) AS mnth
from FrcstFactTbl
) frcst
And of course replace the first line:
SELECT MONTH(frcst.InvDate) AS mnth
With
SELECT mnth
Thank you all. Below is the query that finally worked.
SELECT
masterlist.Month AS [Month]
,masterlist.LineCode AS [Line Code]
,masterlist.ClassCode AS [Class Code]
,ct.cc_type AS [Class Code Type]
,pop.pop_code AS [Pop Code]
,ah.keycust1 AS [Key Cust1]
,ah.keycust2 AS [KeyCust2 - Territory]
,ah.keycust3 AS [Key cust3]
,ah.sales1 AS [Sales1]
,ah.sales2 AS [Sales2]
,ah.sales3 AS [Sales3]
,SUM(ff2017.[Gross]) AS [2017 Gross]
,SUM (ff2017.QtyShip + ( (ff2017.QtyOrd - ff2017.QtyShip) * 0.25) ) AS [2017 Forecast Qty]
,SUM(ff2018.[Gross]) AS [2018 Gross]
,SUM (ff2018.QtyShip + ( (ff2018.QtyOrd - ff2018.QtyShip) * 0.25) ) AS [2018 Forecast Qty]
,SUM(ff2019.[Gross]) AS [2019 Gross]
,SUM (ff2019.QtyShip + ( (ff2019.QtyOrd - ff2019.QtyShip) * 0.25) ) AS [2019 Forecast Qty]
,SUM(ff2020.[Gross]) AS [2020 Gross]
,SUM (ff2020.QtyShip + ( (ff2020.QtyOrd - ff2020.QtyShip) * 0.25) ) AS [2020 Forecast Qty]
FROM (
SELECT
DISTINCT ff.AccountNumber, MONTH(InvDate) AS Month,LineCode,ClassCode,ff.PartNumber
FROM FrcstFactTbl ff
) AS masterlist
LEFT OUTER JOIN
(
SELECT
AccountNumber
,PartNumber
,Month(InvDate) AS Month
,SUM(GrossSales) AS [Gross]
,SUM (QtyShip) AS [QtyShip]
,SUM(QtyOrd) AS [QtyOrd]
FROM FrcstFactTbl WHERE Year(InvDate)=2017
GROUP BY AccountNumber, PartNumber, Month(InvDate)
) AS ff2017 ON masterlist.Month = ff2017.Month AND masterlist.AccountNumber = ff2017.AccountNumber AND masterlist.PartNumber = ff2017.PartNumber
LEFT OUTER JOIN
(
SELECT
AccountNumber
,PartNumber
,Month(InvDate) AS Month
,SUM(GrossSales) AS [Gross]
,SUM (QtyShip) AS [QtyShip]
,SUM(QtyOrd) AS [QtyOrd]
FROM FrcstFactTbl WHERE Year(InvDate)=2018
GROUP BY AccountNumber, PartNumber, Month(InvDate)
) AS ff2018 ON masterlist.Month = ff2018.Month AND masterlist.AccountNumber = ff2018.AccountNumber AND masterlist.PartNumber = ff2018.PartNumber
LEFT OUTER JOIN
(
SELECT
AccountNumber
,PartNumber
,Month(InvDate) AS Month
,SUM(GrossSales) AS [Gross]
,SUM (QtyShip) AS [QtyShip]
,SUM(QtyOrd) AS [QtyOrd]
FROM FrcstFactTbl WHERE Year(InvDate)=2019
GROUP BY AccountNumber, PartNumber, Month(InvDate)
) AS ff2019 ON masterlist.Month = ff2019.Month AND masterlist.AccountNumber = ff2019.AccountNumber AND masterlist.PartNumber = ff2019.PartNumber
LEFT OUTER JOIN
(
SELECT
AccountNumber
,PartNumber
,Month(InvDate) AS Month
,SUM(GrossSales) AS [Gross]
,SUM (QtyShip) AS [QtyShip]
,SUM(QtyOrd) AS [QtyOrd]
FROM FrcstFactTbl WHERE Year(InvDate)=2020
GROUP BY AccountNumber, PartNumber, Month(InvDate)
) AS ff2020 ON masterlist.Month = ff2020.Month AND masterlist.AccountNumber = ff2020.AccountNumber AND masterlist.PartNumber = ff2020.PartNumber
LEFT OUTER JOIN cc_type_lu ct ON masterlist.ClassCode = ct.class_code
LEFT OUTER JOIN pop_code_lu pop ON masterlist.PartNumber = pop.PartNumber
LEFT OUTER JOIN account_hierarchy_lu ah ON masterlist.AccountNumber = ah.account_number
--ORDER BY masterlist.Month
GROUP BY masterlist.Month
,masterlist.LineCode
,masterlist.ClassCode
,ct.cc_type
,pop.pop_code
,ah.keycust1
,ah.keycust2
,ah.keycust3
,ah.sales1
,ah.sales2
,ah.sales3

Error (Conversion failed when converting date and/or time from character string) while executing the view

When I execute this view I get this error:-
Conversion failed when converting date and/or time from character string
Please help me out what kind of mistake I'm making in this given query??*
SQL Query:
WITH CTE_aacd1 AS (
SELECT *
FROM (
SELECT LEAD_CO_MNE
,ACCOUNT_NO
,CLOSURE_TYPE
,DATE_TIME
,Rank() OVER (ORDER BY [DATE_TIME]) AS rank_
FROM [InsightSource].BS.AA_ACCOUNT_CLOSURE_DETAILS
) aat
WHERE aat.rank_ = 1
)
SELECT [Date].BusinessDate as [BusinessDate] , aa.LEAD_CO_MNE as LeadCompany , 'BS' as SourceSystem , concat('BS:' , com.FINANCIAL_MNE , ':' , cast(aa.[LINKED_APPL_ID] as nvarchar(50))) as [SourceAccountId] , concat('BS:' ,CO_CHK.COMPANY_MNE , ':' , CAST(isnull(A.[CO_CODE], aa.[CO_CODE]) as nvarchar(50))) as [SourceBranchId] , concat('BS:' , COM.CUSTOMER_MNEMONIC , ':' , cast(isnull(A.[CUSTOMER], aa.[CUSTOMER]) as nvarchar(50))) as [SourceCustomerId] , concat('BS:' , CO_CHK.COMPANY_MNE , ':' , cast(A.[ACCOUNT_OFFICER] as nvarchar(50))) as [SourceEmployeeId] , concat('BS:' , com.CUSTOMER_MNEMONIC , ':' , l.[#id]) as [SourceLimitId] --,A.[CATEGORY] as [sourceGLId] ,aa.[LINKED_APPL_ID] as [AccountNum]
,-1 * Rb.Debitbal as Balance ,-1 * rb.ForeignDebitBal as [ForeignCurrencyBal] ,'Loan' as [Category] ,A.[CURRENCY] as [Currency] ,-1 * rb.InterestAccrued as [InterestAccrued] ,rb.InterestRate as InterestRate ,rb.FixOrVAr ,rb.Rate_tier_type as RateType --,rb.InterestRateIndex ,rb.InterestRateVariance ,p.[#ID] as [ProductCode] ,P.DESCRIPTION as [ProductDesc] ,aa.PRODUCT_GROUP as [ProductType] ,aa.PRODUCT_GROUP as [T24ProductGroup] ,aa.[START_DATE] as [StartDate] ,isnull(aa.ORIG_CONTRACT_DATE, aa.[START_DATE]) OriginalStartDate ,case when a.INACTIV_MARKER = 'Y' then 'InActive' else AA.[ARR_STATUS] end as [StatusCode] ,a.[ACCOUNT_TITLE_1] as [StatementDesc] ,isnull(aacd.RENEWAL_DATE, aacd.MATURITY_DATE) as MaturityDate ,cast(aacd.MATURITY_DATE as date) as AmortMatureDate ,cast(aata.[AMOUNT] as decimal (28,4)) as OriginalLoanAmount ,cast(aata.[AMOUNT] as decimal (28,4)) as Authorized ,right(rtrim(Isnull(aacp.CHANGE_PERIOD, aata.TERM)), 1) as TermUnit ,try_convert(int,SUBSTRING( Isnull(aacp.CHANGE_PERIOD, aata.TERM), 1, len(isnull(aacp.CHANGE_PERIOD, aata.TERM))-1 )) as Term ,case when right(rtrim(Isnull(aacp.CHANGE_PERIOD, aata.TERM)), 1) = 'M' then try_convert(int,SUBSTRING(Isnull(aacp.CHANGE_PERIOD, aata.TERM), 1, len(Isnull(aacp.CHANGE_PERIOD, aata.TERM))-1 )) when right(rtrim(Isnull(aacp.CHANGE_PERIOD, aata.TERM)), 1) = 'D' then try_convert(int,round(try_convert(int,SUBSTRING(Isnull(aacp.CHANGE_PERIOD, aata.TERM), 1, len(Isnull(aacp.CHANGE_PERIOD, aata.TERM))-1 ))*(1/(365.25/12)) , 0)) when right(rtrim(Isnull(aacp.CHANGE_PERIOD, aata.TERM)), 1) = 'Y' then try_convert(int,round(try_convert(int,SUBSTRING( Isnull(aacp.CHANGE_PERIOD, aata.TERM), 1, len(Isnull(aacp.CHANGE_PERIOD, aata.TERM))-1 ))*12 , 0))
else NULL end as TermInMonths, case when right(rtrim(Isnull(aacp.CHANGE_PERIOD, aata.TERM)), 1) = 'M' then try_convert(int,round(try_convert(int,SUBSTRING( Isnull(aacp.CHANGE_PERIOD, aata.TERM), 1, len(Isnull(aacp.CHANGE_PERIOD, aata.TERM))-1 ))*30.44,0)) when right(rtrim(Isnull(aacp.CHANGE_PERIOD, aata.TERM)), 1) = 'D' then try_convert(int,SUBSTRING( Isnull(aacp.CHANGE_PERIOD, aata.TERM), 1, len(Isnull(aacp.CHANGE_PERIOD, aata.TERM))-1 )) when right(rtrim(Isnull(aacp.CHANGE_PERIOD, aata.TERM)), 1) = 'Y' then try_convert(int,round(try_convert(int,SUBSTRING( Isnull(aacp.CHANGE_PERIOD, aata.TERM), 1, len(Isnull(aacp.CHANGE_PERIOD, aata.TERM))-1 ))*365.25 , 0)) else NULL end as TermInDays ,aacd.[START_DATE] as DisburseDate ,case when aacd.ARR_AGE_STATUS = 'DEL' then 'Yes' else 'No' end as IsDelinquent ,del.DelinquentAmount ,del.LastDelinquentDate -- (!!! ERROR !!!),case when LastDelinquentDate is not null and isdate(del.LastDelinquentDate) = 1 then datediff( d, del.LastDelinquentDate, date.BusinessDate ) end as DelinquentDays ,case when (LastDelinquentDate is not null) and (TRY_CONVERT(DATE, del.LastDelinquentDate) IS NOT NULL) then datediff(d, TRY_CONVERT(DATE, del.LastDelinquentDate), [date].BusinessDate ) end as DelinquentDays ,aacd1.CLOSURE_TYPE as ReasonClosed ,cast(left('20' + aacd1.DATE_TIME, 8) as date) as ClosedDate ,-1 * rb.DebitBal as [AvailableFunds] ,left(arrschedule.Start_date, 8) as FirstPmtDate ,arrschedule.Calc_Amount as ScheduledPmtAmt ,case when payment_freq like '%e1M%' and payment_freq not like '%o%,%D%' then 'Monthly' when payment_freq like '%e1M%' and payment_freq like '%o%,%D%' then 'Twice a month' when payment_freq like '%e2M%' and payment_freq not like '%o%,%D%' then 'Every 2 month' when payment_freq like '%e2M%' and payment_freq like '%o%,%D%' then 'Twice every 2 month' when payment_freq like '%e1W%' or payment_freq like '%e7D%' then 'Weekly' when payment_freq like '%e2W%' or payment_freq like '%e14D%' then 'Bi-Weekly' else 'N/A' end as PmtFreq ,case when intfreq like '%e1M%' and intfreq not like '%o%,%D%' then 'Monthly' when intFreq like '%e1M%' and intfreq like '%o%,%D%' then 'Twice a month' when intFreq like '%e2M%' and intfreq not like '%o%,%D%' then 'Every 2 month' when intFreq like '%e2M%' and intfreq like '%o%,%D%' then 'Twice every 2 month' when payment_freq like '%e1W%' or payment_freq like '%e7D%' then 'Weekly' when payment_freq like '%e2W%' or payment_freq like '%e14D%' then 'Bi-Weekly' else 'N/A' end as InterestPaidFreq , arrschedule.payment_type as PmtCalcMethod ,'BSAA_Lending' as SystemSource FROM [InsightSource].[BS].[AA_ARRANGEMENT] aa LEFT JOIN [InsightSource].[BS].[COMPANY] COM ON COM.MNEMONIC = AA.BRANCH_CO_MNE LEFT JOIN [InsightSource].[BS].[COMPANY_CHECK_Company_Mne] CO_CHK ON CO_CHK.[#ID] = 'MASTER' and CO_CHK.[Sequence] = 1 LEFT JOIN [InsightSource].[BS].[ACCOUNT] a ON a.LEAD_CO_MNE = COM.FINANCIAL_MNE AND A.[#ID] = aa.LINKED_APPL_ID LEFT JOIN [InsightSource].BS.LIMIT l ON a.CUSTOMER +'.' + RIGHT ( '0000' + a.LIMIT_REF , 10) = l.[#ID] AND l.LEAD_CO_MNE = COM.CUSTOMER_MNEMONIC LEFT JOIN (Select del1.[#id], DEL1.ARRANGEMENT_ID, Del1.LEAD_CO_MNE, del1.LastDelinquentDate, SUM(cast(bd.OS_TOTAL_AMOUNT as decimal (28,4))) as DelinquentAmount from
(select aad.[#id], AAD.LEAD_CO_MNE, AAD.ARRANGEMENT_ID, min(billpay.Bill_Pay_date) as LastDelinquentDate, max(billpay.Bill_Pay_date) as MaxDelinquentDate
from
( select [#id], [LEAD_CO_MNE], ARR_AGE_STATUS, [#ID] AS ARRANGEMENT_ID, BILL_PAY_DATE from [InsightSource].BS.AA_ACCOUNT_DETAILS where ARR_AGE_STATUS in ('NAB', 'DEL')) aad join
( select * from [InsightSource].BS.AA_ACCOUNT_DETAILS_Bill_Pay_date where Aging_Status
= 'DEL' or bill_status = 'Aging') billpay on aad.[#id] = billpay.[#id] and aad.[LEAD_CO_MNE] = billpay.[LEAD_CO_MNE]
group by aad.[#id], AAD.ARRANGEMENT_ID, aad.[LEAD_CO_MNE]
) Del1
join
[InsightSource].BS.AA_BILL_DETAILS bd on del1.LEAD_CO_MNE = bd.LEAD_CO_MNE AND bd.[ARRANGEMENT_ID] = DEL1.ARRANGEMENT_ID --and del1.MaxDelinquentDate = bd.actual_pay_date Group by del1.[#id], DEL1.ARRANGEMENT_ID, del1.[LEAD_CO_MNE], del1.LastDelinquentDate )del ON AA.LEAD_CO_MNE = DEL.LEAD_CO_MNE AND AA.[#ID] = DEL.ARRANGEMENT_ID LEFT JOIN (select LEAD_CO_MNE, ID_COMP_1, replace (max(CHANGE_PERIOD) , 'R_BIRTH + ' , '') as CHANGE_PERIOD from [InsightSource].BS.AA_ARR_CHANGE_PRODUCT arr1 where ID_COMP_3 = (select MAX (ID_COMP_3) from [InsightSource].BS.AA_ARR_CHANGE_PRODUCT arr2 where arr1.ID_COMP_1 = arr2.ID_COMP_1 ) group by ID_COMP_1, LEAD_CO_MNE ) aacp ON COM.FINANCIAL_MNE = aacp.LEAD_CO_MNE AND AA.[#ID] = aacp.ID_Comp_1 LEFT JOIN CTE_aacd1 aacd1 ON aacd1.LEAD_CO_MNE = COM.CUSTOMER_MNEMONIC AND aacd1.ACCOUNT_NO = A.[#ID] LEFT JOIN ( SELECT * FROM ( SELECT [#ID]
,[LEAD_CO_MNE]
,PRODUCT
,PRODUCT_STATUS
,Rank() OVER (partition by [#id]
ORDER BY [PROD_EFF_DATE]
) AS rank_
FROM [InsightSource].BS.AA_ARRANGEMENT_PRODUCT
where [PRODUCT_STATUS] = 'CURRENT'
) aap1 WHERE aap1.rank_ = 1 ) aap ON aa.[#ID] = aap.[#ID] AND AAP.[LEAD_CO_MNE] = COM.[FINANCIAL_MNE]
LEFT JOIN [InsightSource].BS.AA_PRODUCT p ON CASE WHEN COM.SPCL_FIN_FILE IS NULL THEN COM.DEFAULT_FINAN_MNE ELSE COM.SPCL_FIN_MNE END = P.BRANCH_CO_MNE AND AAP.PRODUCT = P.[#ID] LEFT JOIN [InsightSource].BS.AA_ACCOUNT_DETAILS aacd ON aacd.[LEAD_CO_MNE] = COM.FINANCIAL_MNE AND aacd.[#ID] = aa.[#ID] LEFT JOIN ( select ps.[#id] ,ps.LEAD_CO_MNE, ps.ID_Comp_1 , ps.Base_date, sfi.Calc_Amount, sf.Actual_amt, sf.payment_freq , sf.payment_type , ps.Start_date, SFI.DUE_FREQ as intFreq ,case when sf.payment_freq like '%e1M%' and sf.payment_freq not like '%o%,%D%' then 1
when sf.payment_freq like '%e1M%' and sf.payment_freq like '%o%,%D%' then 2
when sf.payment_freq like '%e2M%' and sf.payment_freq like '%o%,%D%' then 1
when sf.payment_freq like '%e1W%' then 4
when sf.payment_freq like '%e2W%' then 2
end as NumPmtInOneMonth from [InsightSource].bs.AA_ARR_PAYMENT_SCHEDULE ps join [InsightSource].bs.AA_ARR_PAYMENT_SCHEDULE_payment_freq sf on
ps.[#id] = sf.[#id] and ps.[LEAD_CO_MNE] = sf.[LEAD_CO_MNE] and sequence = 1 left join [InsightSource].bs.AA_ARR_PAYMENT_SCHEDULE_payment_freq_property sfi on ps.[#id] = sfi.[#id] and ps.[lead_co_mne] = sfi.[lead_co_mne] and sfi.property = 'INTEREST' and sfi.MVsequence = 1 and sfi.sequence = 1 where ps.id_comp_3 = (select MAX (id_comp_3) from [InsightSource].BS.AA_ARR_PAYMENT_SCHEDULE arr2 where ps.ID_COMP_1 = arr2.ID_COMP_1 ) and sfi.Calc_Amount is not null group by ps.LEAD_CO_MNE,ps.[#id] , ps.ID_Comp_1, ps.Base_date, sfi.Calc_Amount, sf.Actual_amt, sf.payment_freq , sf.payment_type , ps.Start_date ,SFI.DUE_FREQ, [bill_produced] ) arrSchedule ON aa.LEAD_CO_MNE = arrSchedule.LEAD_CO_MNE AND AA.[#ID] = arrSchedule.ID_Comp_1 LEFT JOIN (select LEAD_CO_MNE,max(REVOLVING) as REVOLVING, max(TERM) as TERM, max(AMOUNT) as amount, ID_COMP_1 from [InsightSource].BS.AA_ARR_TERM_AMOUNT arr1 where ID_COMP_3 = (select MAX (ID_COMP_3) from [InsightSource].BS.AA_ARR_TERM_AMOUNT arr2 where arr1.ID_COMP_1 = arr2.ID_COMP_1 ) group by ID_COMP_1,LEAD_CO_MNE ) aata ON COM.FINANCIAL_MNE = aata.LEAD_CO_MNE AND AA.[#ID] = aata.ID_Comp_1 LEFT JOIN [v_sourceAccountBSAA_RatesandBalances] rb ON rb.[Linked_appl_id] = aa.LINKED_APPL_ID and rb.Lead_co_mne = aa.LEAD_CO_MNE CROSS JOIN [InsightStaging].[dbo].[v_sourceDate] as [Date] WHERE aa.PRODUCT_LINE = 'LENDING' and aa.[LINKED_APPL_ID] is not null

How to get column total for a table with two pivots

I have created a table joining two table having two pivots, Now I intend to get the total of all the column values for each row.
Below is my code which I am currently working on:
SELECT
*
FROM
(SELECT
time_tracker.date,
Users.FirstName + ' ' + Users.LastName AS username,
(CASE
WHEN ((datepart(hour, chk_in)) >= 12 OR
(datepart(hour, chk_out)) < 16)
THEN 0.5
ELSE 1
END) AS late,
TypeOfLeaves.leave_type, Userleavetyp.no_of_days
FROM
Users
INNER JOIN
time_tracker ON Users.ID = time_tracker.fk_userid
INNER JOIN
Userleavetyp ON Users.ID = Userleavetyp.fk_user
INNER JOIN
TypeOfLeaves ON Userleavetyp.fk_tol = TypeOfLeaves.ID
WHERE
(Users.FK_Status = 1)) AS P
For month days
PIVOT
(SUM(late) FOR date IN ("2018-01-01", "2018-01-02", "2018-01-03", "2018-01-04", "2018-01-05", "2018-01-06", "2018-01-07", "2018-01-08", "2018-01-09", "2018-01-10", "2018-01-11", "2018-01-12", "2018-01-13", "2018-01-14", "2018-01-15", "2018-01-16", "2018-01-17", "2018-01-18", "2018-01-19", "2018-01-20", "2018-01-21", "2018-01-22", "2018-01-23", "2018-01-24", "2018-01-25", "2018-01-26", "2018-01-27", "2018-01-28", "2018-01-29", "2018-01-30", "2018-01-31")
) AS pv1
For leave type
PIVOT
(SUM(no_of_days)
FOR leave_type IN ([Casual Leave], [Paid Leave], [Complimentary Leave])) AS pv2
I want the desired result to be something like this
enter image description here
Two things you can do:
Sum all pivoted columns: add an additional expression that sums all results. Change:
SELECT
*
FROM
--...
To:
SELECT
*,
Total = ISNULL([2018-01-01], 0)
+ ISNULL([2018-01-02], 0)
+ ISNULL([2018-01-03], 0)
+ ISNULL([2018-01-04], 0)
+ ISNULL([2018-01-05], 0)
+ ISNULL([2018-01-06], 0)
+ ISNULL([2018-01-07], 0)
+ ISNULL([2018-01-08], 0)
+ ISNULL([2018-01-09], 0)
+ ISNULL([2018-01-10], 0)
+ ISNULL([2018-01-11], 0)
+ ISNULL([2018-01-12], 0)
+ ISNULL([2018-01-13], 0)
+ ISNULL([2018-01-14], 0)
+ ISNULL([2018-01-15], 0)
+ ISNULL([2018-01-16], 0)
+ ISNULL([2018-01-17], 0)
+ ISNULL([2018-01-18], 0)
+ ISNULL([2018-01-19], 0)
+ ISNULL([2018-01-20], 0)
+ ISNULL([2018-01-21], 0)
+ ISNULL([2018-01-22], 0)
+ ISNULL([2018-01-23], 0)
+ ISNULL([2018-01-24], 0)
+ ISNULL([2018-01-25], 0)
+ ISNULL([2018-01-26], 0)
+ ISNULL([2018-01-27], 0)
+ ISNULL([2018-01-28], 0)
+ ISNULL([2018-01-29], 0)
+ ISNULL([2018-01-30], 0)
+ ISNULL([2018-01-31], 0)
FROM
--...
Calculate the total on another subquery and join at the end to retrieve the total:
;WITH ToPivot AS
(
SELECT
time_tracker.date,
Users.FirstName + ' ' + Users.LastName AS username,
(CASE
WHEN ((datepart(hour, chk_in)) >= 12 OR
(datepart(hour, chk_out)) < 16)
THEN 0.5
ELSE 1
END) AS late,
TypeOfLeaves.leave_type,
Userleavetyp.no_of_days
FROM
Users
INNER JOIN
time_tracker ON Users.ID = time_tracker.fk_userid
INNER JOIN
Userleavetyp ON Users.ID = Userleavetyp.fk_user
INNER JOIN
TypeOfLeaves ON Userleavetyp.fk_tol = TypeOfLeaves.ID
WHERE
(Users.FK_Status = 1)
),
LateTotals AS
(
SELECT
T.username,
Total = SUM(late)
FROM
ToPivot AS T
WHERE
T.date IN ('2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04', '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08', '2018-01-09', '2018-01-10', '2018-01-11', '2018-01-12', '2018-01-13', '2018-01-14', '2018-01-15', '2018-01-16', '2018-01-17', '2018-01-18', '2018-01-19', '2018-01-20', '2018-01-21', '2018-01-22', '2018-01-23', '2018-01-24', '2018-01-25', '2018-01-26', '2018-01-27', '2018-01-28', '2018-01-29', '2018-01-30', '2018-01-31')
GROUP BY
T.username
)
SELECT
PV2.*,
L.Total
FROM
ToPivot AS P
PIVOT
(SUM(late) FOR date IN ("2018-01-01", "2018-01-02", "2018-01-03", "2018-01-04", "2018-01-05", "2018-01-06", "2018-01-07", "2018-01-08", "2018-01-09", "2018-01-10", "2018-01-11", "2018-01-12", "2018-01-13", "2018-01-14", "2018-01-15", "2018-01-16", "2018-01-17", "2018-01-18", "2018-01-19", "2018-01-20", "2018-01-21", "2018-01-22", "2018-01-23", "2018-01-24", "2018-01-25", "2018-01-26", "2018-01-27", "2018-01-28", "2018-01-29", "2018-01-30", "2018-01-31")
) AS pv1
PIVOT
(SUM(no_of_days)
FOR leave_type IN ([Casual Leave], [Paid Leave], [Complimentary Leave])
) AS pv2
LEFT JOIN LateTotals AS L ON L.username = pv2.username

Query Runs Slower The Second Time

I have this massive query that I can typically run in under 2 minutes. However, when I run it a second time about a minute after, it goes on infinitely... so I kill the process and my SSMS session. I don't have any other jobs running in the background.
Is something else being retained on the server? I think I'm missing something as far as how SQL Server works.
Thanks.
EDIT: Here's the SQL (had to do a little obfuscation)
SELECT pl.OrangeLocationID ,
e.EventID ,
cr.Title AS [Event Type] ,
su.LastName + ', ' + su.FirstName AS FMR ,
CONVERT(VARCHAR(20), pl.Report_Date, 101) AS [Report Entry Date] ,
l.Name ,
l.Number ,
ll.SodaPopLocationID AS [SodaPop Location ID] ,
l.Zip ,
c.Channel ,
pl.DT AS [ReportedDate] ,
RIGHT(pl.DT_start, 8) AS [ReportedStartTime] ,
RIGHT(pl.DT_end, 8) AS [ReportedEndTime] ,
[CMS].dbo.dDateDiff(pl.DT_start, pl.DT_end) AS [ReportedDuration] ,
pl.scheduled_date AS [ScheduledDate] ,
RIGHT(pl.scheduled_start, 8) AS [ScheduledStartTime] ,
RIGHT(pl.scheduled_end, 8) AS [ScheduledEndTime] ,
[CMS].dbo.dDateDiff(pl.scheduled_start, pl.DT_end) AS [ScheduledDuration] ,
e.HoursPaid AS [Rep Hours Worked] ,
ISNULL(PP.[RepCount], 0) AS [RepCount] ,
CASE WHEN [CMS].dbo.dDateDiff(pl.DT_start, pl.DT_end) = ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
THEN [CMS].dbo.oa_HourDateDiff(pl.DT_start, pl.DT_end)
WHEN [CMS].dbo.dDateDiff(pl.scheduled_start, pl.DT_end) = ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
THEN [CMS].dbo.oa_HourDateDiff(pl.scheduled_start, pl.DT_end)
ELSE ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
END AS [FinalDuration] ,
g.[Description] AS [OA Market] ,
g.SodaPop_Region AS [SodaPop Region] ,
g.SodaPop_Area AS [SodaPop Area] ,
coup4 ,
coupo ,
coupo_e ,
card_num ,
promo ,
promo_no ,
promo_no_o ,
highlight1 ,
highlight2 ,
highlight3 ,
mgmt_reaction ,
mgmt_reaction_e ,
comm_p ,
comm_n ,
r.comments ,
s_fname ,
s_lname ,
v_title ,
ll.KeyAccountCorp AS [Key Account Corp.] ,
interact_new + interact_rep AS [interact_total] ,
samp_new + samp_rep AS [samp_total] ,
purch_new + purch_rep AS [purch_total] ,
23 / ( NULLIF(( interact_new + interact_rep ), 0) * 1.0 ) AS [Int_Crate] ,
CASE WHEN sampletype = 11 THEN ( purch_new + purch_rep ) / ( NULLIF(( samp_new + samp_rep ), 0) * 1.0 )
ELSE NULL
END AS [Samp_Crate] ,
coup1 + coup2 AS [coup_total] ,
CASE WHEN coup1 + coupo > 0 THEN 1
ELSE 0
END AS [CoupDist] ,
DATEPART(month, pl.DT) AS [Visit_Month] ,
DATEPART(quarter, pl.DT) AS [Quarter] ,
DATEPART(weekday, pl.DT) AS [Weekday] ,
CASE DATEPART(weekday, pl.DT)
WHEN 6 THEN 'Fri'
WHEN 7 THEN 'Sat'
WHEN 1 THEN 'Sun'
ELSE 'Mon-Thurs'
END AS [Weekday_Grouped] ,
CASE WHEN dbo.Exception(pl.OrangeLocationID, 12) = 1
OR dbo.Exception(pl.OrangeLocationID, 13) = 1
OR dbo.Exception(pl.OrangeLocationID, 14) = 1 THEN 1
ELSE 0
END AS [EVolume] ,
CASE WHEN dbo.DoesHaveException(pl.OrangeLocationID, 18) = 1 THEN 1
ELSE 0
END AS [CVolume] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 9) = 1
OR dbo.eException(pl.OrangeLocationID, 22) = 1 THEN 1
ELSE 0
END AS [Volumes] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 8) = 1
OR dbo.eException(pl.OrangeLocationID, 21) = 1 THEN 1
ELSE 0
END AS [Sales Price] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 11) = 1 THEN 1
ELSE 0
END AS [Sample Volume] ,
ISNULL(i.[NormalizedSold], 0) AS [EQBottlesSold] ,
CASE WHEN ISNULL(purch_new, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END AS [EQBottlesSoldPerPurch] ,
ac.AvgSales ,
ac.STDEVSales ,
( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales AS [sl] ,
ac.AvgPurchasers ,
ac.STDEVPurchasers ,
( ISNULL(r.purch_new, 0) - ac.AvgPurchasers ) / ac.STrchasers AS [ZScore_Purchasers] ,
ac.AvgConversions ,
ac.STDEVConversions ,
( ISNULL(( purch_new + purch_rep ) / ( NULLIF(( interact_new ), 0) ), 0) - ac.AvgConversions )
/ ac.STDEVConversions AS [ZScore_Conversions] ,
ac.[AvgSalesPerPurchaser] ,
ac.[STDEVSalesPerPurchaser] ,
( ISNULL(( CASE WHEN ISNULL(purch_new, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END ), 0) - ac.[AvgSalesPerPurchaser] ) / ac.[STDEVSalesPerPurchaser] AS [SalesPerPurchaser] ,
( ( ( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales )
+ ( (ISNULL(( CASE WHEN ISNULL(purch_new + purch_rep, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END ), 0) - ac.[AvgSalesPerPurchaser]) ) ) / 4 AS [core] ,
( ( (( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales) ) / 4 ) + 3 AS [core] ,
su.aaUserID ,
l.LsocationID
FROM [CMS_SodaPop].dbo.Schedule pl WITH ( NOLOCK )
INNER JOIN [CMS_SodaPop].dbo.Report r WITH ( NOLOCK ) ON r.OrangeLocationID = pl.OrangeLocationID
INNER JOIN [CMS].dbo.Users su WITH ( NOLOCK ) ON su.UserID = pl.Rep_FMR
INNER JOIN [CMS].dbo.Locations l WITH ( NOLOCK ) ON l.LocationID = pl.LocationID
INNER JOIN [CMS].dbo.OrangeReports cr WITH ( NOLOCK ) ON cr.RedID = pl.RedID
INNER JOIN [CMS_SodaPop].dbo.Events e WITH ( NOLOCK ) ON e.OrangeLocationID = pl.OrangeLocationID
INNER JOIN [CMS_SodaPop].dbo.MarketList g WITH ( NOLOCK ) ON g.GroupID = pl.GroupID
INNER JOIN [CMS_SodaPop].dbo.Locations ll WITH ( NOLOCK ) ON ll.LocationID = pl.LocationID
LEFT JOIN [CMS_SodaPop].dbo.Channels c WITH ( NOLOCK ) ON ll.ChannelID = c.ChannelID
LEFT JOIN ( SELECT PLocationID ,
COUNT(DISTINCT UserID) AS [RepCount]
FROM [CMS_roll].dbo.rollItems WITH ( NOLOCK )
WHERE RedID = 154
GROUP BY OrangeLocationID
) PP ON PP.OrangeLocationID = pl.OrangeLocationID
LEFT JOIN ( SELECT OrangeLocationID ,
SUM(NormalizedSold) AS [NormalizedSold]
FROM [Analysis].dbo.[vSodaPop_Retail_Inventory] WITH ( NOLOCK )
GROUP BY OrangeLocationID
) i ON i.OrangeLocationID = pl.OrangeLocationID
LEFT JOIN [Analysis].dbo.[vSodaPop_Calculations] ac WITH ( NOLOCK ) ON ac.[Quarter] = CASE WHEN DATEPART(MM,
[DT]) IN ( 10,
11, 12 ) THEN 4
END
AND ac.[Year] = DATEPART(YY, pl.DT)
WHERE pl.Activity = 1
AND pl.RedID = 154
AND pl.GroupID <> 444
AND pl.[DT] < GETDATE()
AND DATEPART(YY, [DT]) >= 2010
AND ISNULL(i.NormalizedSold, 0) >= 0
AND DATEPART(year, GETDATE()) = DATEPART(year, r.Insert_Date)
Would have to see the query to really dig in however..
you could try adding OPTION (RECOMPILE) to the end of the query to force it to create a new execution plan.
Are you using Temp Tables?
Cursors not deallocated & closed?
You can look at Profiler to see if anything looks different between the 2 executions.
Are you sure it isn't being blocked by another process the second time?
What happens if you execute
CHECKPOINT;
GO;
DBCC DROPCLEANBUFFERS;
GO;
DBCC FREEPROCCACHE;
GO;
between the queries? This is not really a solution but will help diagnosis.