How to get accumulated data using SUM, GROUP BY function - sql

I beg your pardon for such a lengthy query, but I am in desperate need of help.
When I run the query below, I get daily data. But I want monthly data, using LASTDAY,
SUM, GROUP BY function.
For instance, if I pick '20130501' in #startDt# and '20130701' in #endDt#, it should give me 3 rows of accumulated results; May, June and July. Can anyone help?
SELECT X.*
FROM
(
SELECT
(CASE
WHEN DAY.DAY = 'SUM' THEN DAY.DAY
ELSE TO_CHAR (TO_DATE (DAY.DAY, 'YYYY-MM-DD'), 'YYYYMMDD')
END
) AS DAY,
DAY.WEEK,
MNOT.SUM_STD_CNT AS MNOT_CNT,
RSC.MOVIE_500K AS MOVIE_500K_CNT,
RSC.MOVIE_1M AS MOVIE_1M_CNT,
RSC.MOVIE AS MOVIE_CNT,
RSC.EXAM AS EXAM_CNT,
RSC.WEB AS WEB_CNT,
RSC.IMG AS IMG_CNT,
RSC.INTERRAC AS INTERRACTIVE_CNT,
RSC.DOC AS DOC_CNT,
MNOT.SUM_STD_CNT + RSC.MOVIE_500K + RSC.MOVIE_1M + RSC.MOVIE + RSC.EXAM + RSC.WEB + RSC.IMG + RSC.INTERRAC + RSC.DOC TOT_CNT
FROM
/* DATES */
(SELECT
TO_CHAR (TO_DATE (#startDt#,'YYYY-MM-DD')+LEVEL- 1, 'YYYYMMDD') AS DAY
FROM DUAL
CONNECT BY TO_DATE(#startDt#, 'YYYY-MM-DD') + LEVEL - 1 <![CDATA[<=]]> TO_DATE(#endDt#, 'YYYY-MM-DD')
UNION ALL
SELECT 'SUM', '' FROM DUAL
) DAY LEFT OUTER JOIN
/* RESOURCE */
(
SELECT
NVL(DT_G.COMM_DT, 'SUM') COMM_DT
,NVL(SUM(DT_G.MOVIE_500K), 0) AS MOVIE_500K
,NVL(SUM(DT_G.MOVIE_1M), 0) AS MOVIE_1M
,NVL(SUM(DT_G.MOVIE), 0) AS MOVIE
,NVL(SUM(DT_G.EXAM), 0) AS EXAM
,NVL(SUM(DT_G.DOC), 0) AS DOC
,NVL(SUM(DT_G.IMG), 0) AS IMG
,NVL(SUM(DT_G.WEB), 0) AS WEB
,NVL(SUM(DT_G.INTERRAC), 0) AS INTERRAC
FROM
(
SELECT
COMM_DT
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_500K END MOVIE_500K
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_1M END AS MOVIE_1M
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_500K+SUMT.SUM_1M END AS MOVIE
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP11' THEN SUMT.SUM_STD_CNT END AS EXAM
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP12' THEN SUMT.SUM_STD_CNT END AS DOC
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP13' THEN SUMT.SUM_STD_CNT END AS IMG
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP14' THEN SUMT.SUM_STD_CNT END AS WEB
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP01' THEN SUMT.SUM_STD_CNT END AS INTERRAC
FROM (
SELECT RSC_TP_DSCD, SUM(STDY_CNT) AS SUM_STD_CNT, SUM(MOVIE_STDY_CNT_N1M) AS SUM_1M, SUM(MOVIE_STDY_CNT_N500K) AS SUM_500K, COMM_DT
FROM (
SELECT RSC_SNO, STDY_CNT, MOVIE_STDY_CNT_N1M, MOVIE_STDY_CNT_N500K, COMM_DT
FROM LRMS.V_EBSM_PKG_RSC_COMM_CNT
WHERE PKG_SNO = 0 AND RSC_SNO != 0
AND COMM_DT BETWEEN TO_CHAR(TO_DATE(#startDt#, 'YYYY-MM-DD'), 'YYYYMMDD') AND TO_CHAR(TO_DATE(#endDt#, 'YYYY-MM-DD'), 'YYYYMMDD')
) CNT
LEFT OUTER JOIN LRMS.V_LRRM_RSC RSC ON CNT.RSC_SNO = RSC.RSC_SNO
GROUP BY RSC_TP_DSCD, COMM_DT
) SUMT
) DT_G
GROUP BY ROLLUP(DT_G.COMM_DT)
) RSC ON DAY.DAY = RSC.COMM_DT
LEFT OUTER JOIN
(
SELECT NVL(SUM(STDY_CNT), 0) AS SUM_STD_CNT, NVL(COMM_DT, 'SUM') COMM_DT
FROM LRMS.V_EBSM_PKG_RSC_COMM_CNT
WHERE PKG_SNO != 0 AND RSC_SNO = 0
AND COMM_DT BETWEEN TO_CHAR(TO_DATE(#startDt#, 'YYYY-MM-DD'), 'YYYYMMDD') AND TO_CHAR(TO_DATE(#endDt#, 'YYYY-MM-DD'), 'YYYYMMDD')
GROUP BY ROLLUP(COMM_DT)
) MNOT ON DAY.DAY = MNOT.COMM_DT
) X
WHERE 1=1
and X.TOT_CNT IS NOT NULL

you can do something like
SELECT DATENAME(MONTH , DAY) , SUM(COLUMN1) , SUM(COLUMN2) ..
FROM (YOURQUERY) AS A
GROUP BY DATENAME(MONTH , DAY)
I think this will help you .

Related

Union Query Getting error on sales summary

Here is my code. Two CTES With a subquery and im trying to get the 2ns cte to give me totals like a pivot table.
WITH
SalesSummary AS
(
SELECT
Employee AS RepID,
Type,
SUM( ForeignTotal ) AS ForeignTotal,
SUM( projectedTotal*probability ) AS ProjectedTotal
FROM
Transaction
WHERE
( ( Type = 'SalesOrd' ) AND ( BUILTIN.CF( Status ) IN ('SalesOrd:B','SalesOrd:A') AND TO_CHAR(shipdate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(shipdate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'Opprtnty' ) AND ( BUILTIN.CF( Status ) IN ('Opprtnty:A','Opprtnty:C') AND TO_CHAR(expectedclosedate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(expectedclosedate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'CustInvc' ) AND ( BUILTIN.CF( Status ) IN ('CustInvc:A','CustInvc:B') AND TO_CHAR(trandate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(trandate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'CashSale' ) AND ( BUILTIN.CF( Status ) IN ('CashSale:C','CashSale:B') AND TO_CHAR(trandate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(trandate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'CustCred' ) AND ( BUILTIN.CF( Status ) IN ('CustCred:B','CustCred:A') AND TO_CHAR(trandate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(trandate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
GROUP BY
Employee,
Type
)
,
Totals AS
(
SELECT
NULL AS RepName,
SUM ( CASE WHEN Type = 'Opprtnty' THEN ProjectedTotal ELSE 0 END ) AS Opportunity_Total,
SUM ( CASE WHEN Type = 'SalesOrd' THEN ForeignTotal ELSE 0 END ) AS Sales_Pending_Total,
SUM ( CASE WHEN Type = 'CustInvc' THEN ForeignTotal ELSE 0 END ) AS Invoiced,
SUM ( CASE WHEN Type = 'CashSale' THEN ForeignTotal ELSE 0 END ) AS Cash_Sale,
SUM ( CASE WHEN Type = 'CustCred' THEN ForeignTotal ELSE 0 END ) AS Credit_Memo,
NULL AS forecast
FROM
Transaction
WHERE
( ( Type = 'SalesOrd' ) AND ( BUILTIN.CF( Status ) IN ('SalesOrd:B','SalesOrd:A') AND TO_CHAR(shipdate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(shipdate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'Opprtnty' ) AND ( BUILTIN.CF( Status ) IN ('Opprtnty:A','Opprtnty:C') AND TO_CHAR(expectedclosedate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(expectedclosedate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'CustInvc' ) AND ( BUILTIN.CF( Status ) IN ('CustInvc:A','CustInvc:B') AND TO_CHAR(trandate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(trandate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'CashSale' ) AND ( BUILTIN.CF( Status ) IN ('CashSale:C','CashSale:B') AND TO_CHAR(trandate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(trandate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'CustCred' ) AND ( BUILTIN.CF( Status ) IN ('CustCred:B','CustCred:A') AND TO_CHAR(trandate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(trandate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
)
SELECT
a.RepName,
a.Opportunity_Total,
a.Sales_Pending_Total,
a.Invoiced,
a.Cash_Sale,
a.Credit_Memo,
case when (a.Sales_Pending_Total + a.Invoiced + a.Cash_Sale + a.Credit_Memo) < Opportunity_Total
then Opportunity_Total*-1
else (a.Sales_Pending_Total + a.Invoiced + a.Cash_Sale + a.Credit_Memo) END as forecast
from(
SELECT
RepID,
( Employee.FirstName || ', ' || Employee.LastName ) AS RepName,
SUM ( CASE WHEN Type = 'Opprtnty' THEN ProjectedTotal ELSE 0 END ) AS Opportunity_Total,
SUM ( CASE WHEN Type = 'SalesOrd' THEN ForeignTotal ELSE 0 END ) AS Sales_Pending_Total,
SUM ( CASE WHEN Type = 'CustInvc' THEN ForeignTotal ELSE 0 END ) AS Invoiced,
SUM ( CASE WHEN Type = 'CashSale' THEN ForeignTotal ELSE 0 END ) AS Cash_Sale,
SUM ( CASE WHEN Type = 'CustCred' THEN ForeignTotal ELSE 0 END ) AS Credit_Memo,
FROM
SalesSummary
INNER JOIN Employee ON
( Employee.ID = SalesSummary.RepID )
WHERE
RepID IN ('17','24','-5','26')
GROUP BY
RepID,
( Employee.FirstName || ', ' || Employee.LastName )
ORDER BY
RepName
) a
UNION
SELECT
RepName,
Opportunity_Total,
Sales_Pending_Total,
Invoiced,
Cash_Sale,
Credit_Memo,
forecast
FROM
Totals

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

How to get accumulated-monthly data using query

When I run this query, it should display 3 rows of result under DAY column (210301, 201302, SUM).But for some reason, it only shows SUM row under DAY column. Idea is that '201301' row accumulates 31 days of data in January.
Can anyone point me out why they don't show up?
SELECT X.*
FROM
(
SELECT
(CASE
WHEN DAY.DAY = 'SUM' THEN DAY.DAY
ELSE
TO_CHAR (TO_DATE (DAY.DAY, 'YYYY-MM'), 'YYYYMM')
END
) AS DAY,
MNOT.SUM_STD_CNT AS MNOT_CNT,
RSC.MOVIE_500K AS MOVIE_500K_CNT,
RSC.MOVIE_1M AS MOVIE_1M_CNT,
RSC.MOVIE AS MOVIE_CNT,
RSC.EXAM AS EXAM_CNT,
RSC.WEB AS WEB_CNT,
RSC.IMG AS IMG_CNT,
RSC.INTERRAC AS INTERRACTIVE_CNT,
RSC.DOC AS DOC_CNT,
MNOT.SUM_STD_CNT + RSC.MOVIE_500K + RSC.MOVIE_1M + RSC.MOVIE + RSC.EXAM + RSC.WEB + RSC.IMG + RSC.INTERRAC + RSC.DOC TOT_CNT
FROM
/* DATES */
(SELECT TO_CHAR(ADD_MONTHS(TO_DATE('201301','YYYYMM'),LEVEL-1), 'YYYYMM') AS DAY
FROM DUAL
CONNECT BY ADD_MONTHS(TO_DATE('201301','YYYYMM'),LEVEL-1 ) <= TO_DATE('201302', 'YYYYMM')
UNION ALL
SELECT 'SUM' FROM DUAL
) DAY LEFT OUTER JOIN
/* RESOURCE */
(
SELECT
NVL(DT_G.COMM_DT, 'SUM') COMM_DT
,NVL(SUM(DT_G.MOVIE_500K), 0) AS MOVIE_500K
,NVL(SUM(DT_G.MOVIE_1M), 0) AS MOVIE_1M
,NVL(SUM(DT_G.MOVIE), 0) AS MOVIE
,NVL(SUM(DT_G.EXAM), 0) AS EXAM
,NVL(SUM(DT_G.DOC), 0) AS DOC
,NVL(SUM(DT_G.IMG), 0) AS IMG
,NVL(SUM(DT_G.WEB), 0) AS WEB
,NVL(SUM(DT_G.INTERRAC), 0) AS INTERRAC
FROM
(
SELECT
COMM_DT
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_500K END MOVIE_500K
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_1M END AS MOVIE_1M
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_500K+SUMT.SUM_1M END AS MOVIE
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP11' THEN SUMT.SUM_STD_CNT END AS EXAM
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP12' THEN SUMT.SUM_STD_CNT END AS DOC
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP13' THEN SUMT.SUM_STD_CNT END AS IMG
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP14' THEN SUMT.SUM_STD_CNT END AS WEB
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP01' THEN SUMT.SUM_STD_CNT END AS INTERRAC
FROM (
SELECT RSC_TP_DSCD, SUM(STDY_CNT) AS SUM_STD_CNT, SUM(MOVIE_STDY_CNT_N1M) AS SUM_1M, SUM(MOVIE_STDY_CNT_N500K) AS SUM_500K, COMM_DT
FROM (
SELECT RSC_SNO, STDY_CNT, MOVIE_STDY_CNT_N1M, MOVIE_STDY_CNT_N500K, COMM_DT
FROM LRMS.V_EBSM_PKG_RSC_COMM_CNT
WHERE PKG_SNO = 0 AND RSC_SNO != 0
AND COMM_DT BETWEEN TO_CHAR(TO_DATE('201301', 'YYYY-MM'), 'YYYYMM') AND TO_CHAR(TO_DATE('201311', 'YYYY-MM'), 'YYYYMMDD')
) CNT
LEFT OUTER JOIN LRMS.V_LRRM_RSC RSC ON CNT.RSC_SNO = RSC.RSC_SNO
GROUP BY RSC_TP_DSCD, COMM_DT
) SUMT
) DT_G
GROUP BY ROLLUP(DT_G.COMM_DT)
) RSC ON DAY.DAY = RSC.COMM_DT
/* MNOTE */
LEFT OUTER JOIN
(
SELECT NVL(SUM(STDY_CNT), 0) AS SUM_STD_CNT, NVL(COMM_DT, 'SUM') COMM_DT
FROM LRMS.V_EBSM_PKG_RSC_COMM_CNT
WHERE PKG_SNO != 0 AND RSC_SNO = 0
AND COMM_DT BETWEEN TO_CHAR(TO_DATE('201301', 'YYYY-MM'), 'YYYYMM') AND TO_CHAR(TO_DATE('201306', 'YYYY-MM'), 'YYYYMM')
GROUP BY ROLLUP(COMM_DT)
) MNOT ON DAY.DAY = MNOT.COMM_DT
) X
WHERE 1=1
and X.TOT_CNT IS NOT NULL
This may be because of the null values in the sum field TOT_CNT
change the line
MNOT.SUM_STD_CNT + RSC.MOVIE_500K + RSC.MOVIE_1M + RSC.MOVIE + RSC.EXAM + RSC.WEB + RSC.IMG + RSC.INTERRAC + RSC.DOC TOT_CNT
to
nvl(MNOT.SUM_STD_CNT,0) + nvl(RSC.MOVIE_500K,0) + nvl(RSC.MOVIE_1M,0) + nvl(RSC.MOVIE,0) + nvl(RSC.EXAM,0) + nvl(RSC.WEB,0) + nvl(RSC.IMG,0) + nvl(RSC.INTERRAC,0) + nvl(RSC.DOC,0) AS TOT_CNT
and try

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.