Optimize multiple query separated by condition - sql

I have a stored procedures with three different queries, that querys return values depending of received variable.
They basically return same data, just change WHERE clauses:
Query:
IF #DesignType = 'BDCD'
BEGIN
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, CONVERT(BIT , IIF([DT].[DesignTypeGuid] = #ContractedDocument , 1 , 0)) AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND ([DT].[DesignTypeGuid] != IIF(#DesignTypeGuid = #ContractedDocument , #BidDocument , #ContractedDocument))
AND [DT].[DesignTypeGuid] != #ChangeOrder
AND [DT].[DesignTypeGuid] != #AddedPart
ORDER BY
[DT].[Order]
END
ELSE
BEGIN
IF #DesignType = 'CO'
BEGIN
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, 0 AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND [DT].[DesignTypeGuid] = #ChangeOrder
ORDER BY
[DT].[Order]
END
ELSE
BEGIN
IF #DesignType = 'AP'
BEGIN
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, 0 AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND [DT].[DesignTypeGuid] = #AddedPart
ORDER BY
[DT].[Order]
END
Is there any way to optimize this and do it in a simple SELECT instead do 3 differents depending of DesignType variable? Regards

Not sure about the performance , but the query could definitely be written as
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, CASE #DesignType WHEN 'BDCD' THEN CONVERT(BIT , IIF([DT].[DesignTypeGuid] = #ContractedDocument , 1 , 0)) ELSE 0 END AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND (
(
#DesignType = 'BDCD' AND [DT].[DesignTypeGuid] NOT IN ( IIF(#DesignTypeGuid = #ContractedDocument , #BidDocument , #ContractedDocument),#ChangeOrder,#AddedPart)
)
OR
(
#DesignType = 'CO' AND [DT].[DesignTypeGuid] = #ChangeOrder
)
OR
(
#DesignType = 'AP' AND [DT].[DesignTypeGuid] = #AddedPart
)
)
ORDER BY
[DT].[Order]

Related

How do I Optimization sql Query and replace CURSOR

How would I Optimize this code removing the cursor
BEGIN TRANSACTION;
BEGIN
if exists (select AgreementNo from PFAgreements where Approved = 1 and finalized = 1 )
begin
if #Agreements <> 'ALL'
BEGIN
SELECT #CursorState = CURSOR_STATUS('global','curAgreement1')
if #CursorState = 1
--The cursor allocated to this variable is open.
--For insensitive and keyset cursors, the result set has at least one row.
--For dynamic cursors, the result set can have zero, one, or more rows
begin
CLOSE curAgreement1
DEALLOCATE curAgreement1
end
else if #CursorState = 0
--The cursor allocated to this variable is open, but the result set is definitely empty.*
begin
CLOSE curAgreement1
DEALLOCATE curAgreement1
end
else if #CursorState = -1
--The cursor allocated to this variable is closed.
begin
DEALLOCATE curAgreement1
end
declare curAgreement1 cursor for
(Select AgreementNo from PFAgreements where Approved = 1 and finalized = 1 AND AgreementNo = #Agreements)
END
ELSE
BEGIN
declare curAgreement1 cursor for
(Select AgreementNo from PFAgreements where Approved = 1 and finalized = 1)
END
open curAgreement1
Fetch next from curAgreement1 into #AgreementAno
while (##fetch_status = 0)
begin
SELECT
#Cno = ISNULL(BaseNo, ''),
#StartDate = CommencementDate,
#MaturityDate = MaturityDate,
#FirstInstalDate = FirstInstallmentDate,
#Tranch = ISNULL(Tranche, 0),
#MyCurrency = ISNULL(Currency, ''),
#Term = ISNULL(NoOfRepayments, 0),
#ApprovedAmount = ISNULL(LoanAppliedAmount , 0),
--#ApprovedAmount = ISNULL(LoanAppliedAmount - deposit , 0),
#IntRate = ISNULL(IntRate, 0),
#Registered = 0,
#RegisteredCollateral = '',
#DisbursementDate = ActivationDate,
#ProdCode = Product,
#CurOfRepayment = CurrencyRepayment
FROM dbo.PFAgreements
WHERE AgreementNo = #AgreementAno
--call saveupdate transitems
--ensures there is no accrual that hasent been paid up in transbill
exec uspsaveupdatetransitems #AgreementAno , #LogIP , #LogUser , #Compname
select #myrate = (select top 1 EXCHRATE from EXCHRATES where Company = #Company and CURRENCYDATE <= #ProcDate and CURRENCYCODE =#MyCurrency order by CURRENCYDATE desc)
select ISNULL(#MyRate , 1)
set #Rental = 0
set #rental = (Select top 1 rental from schedules where AgreementNo = #AgreementAno ORDER BY ID desc)
set #rental = isnull(#rental,0)
If exists(select DateDue from Schedules where agreementno = #AgreementAno)
begin
Set #maturityDate = (Select Max(DateDue) From schedules where AgreementNo = #AgreementAno)
end
set #Names =( Select dbo.GetCustomerNamePF (#AgreementAno))
--deallocate rowcount
set #rowcount =0
set #rowcount = (Select count(AgreementNo) from PFAgreements Where AgreementNo=#AgreementAno and Finalized = 1 and Approved = 1 )
if #rowcount>0
begin
declare #TxRow int
set #TxRow =#rowcount - 1
Declare #TotalInt as numeric(18,2)
select #TotalInt = isnull((Select case when Sum(AmountDue) is null then 0 else Sum(AmountDue) end Amount from Schedules where AgreementNo = #AgreementAno and ItemCode = '11' and Processed = 0 ),0)
--Tom 2017-04-18: Check if there is Written Off or Terminated Interest
select #TerminatedInt = isnull((select UFCBal from IPFTerminatedAgreements where AgreementNo = #AgreementAno ),0)
select #WritenOffInt = isnull((select isnull(sum((AmountDue-AmountPaid)),0) from WriteOffDetails where ContractNo = #AgreementAno and REJECTED=0),0)
--Therefore the Interest Balance
select #TotalInt = #TotalInt - #TerminatedInt - #WritenOffInt
--End of Tom
if #TotalInt < 0
begin
select #TotalInt = 0
end
select #LastCreditDate = ISNULL(dbo.LastCreditDate(#AgreementAno),'1900-01-01'), #NoOFArr = dbo.NoOfArrsModif(#AgreementAno,#ProcDate) ,
#NoOfArrReal = dbo.NoOfArrs(#AgreementAno,#ProcDate) , #nextduedate = isnull(dbo.FirstAccrualDate(#AgreementAno),dbo.FirstAccrualDatePaid(#AgreementAno)) ,
#PrincipalBal = dbo.GetPrinBalBFPF(#AgreementAno,#ProcDate) ,#PrincipalBalBccy = #PrincipalBal * #MyRate ,
--#InterestBal =#TotalInt + ( Select case when Sum(AmountDue) is null then 0 else Sum(AmountDue) end Amount from Trans_Bill where AgreementNo = #AgreementAno and ItemCode = '11' and ReAccrual = 0 ),
#InterestBal =#TotalInt ,
--kenwillis 12042016
--commented line shows initial interest. above new shows interest to maturity un processesd
#InterestBalBccy = ( #InterestBal * #MyRate ) ,
#TrustBal = (Select case when Sum(AmountFcy) IS null then 0 else Sum(AmountFcy) end Amount from ReceiptOverPayments where AgreementNo = #AgreementAno ) ,
#TrustBalBccy = (#TrustBal * #myrate) ,
#OtherBal = (select case when Sum(Amountdue - AmountPaid) IS null then 0 else Sum(Amountdue - AmountPaid) end Amount from Trans_Bill where AgreementNo = #AgreementAno
and DateDue < = #procdate and ItemCode in(Select chargesCode from charges) and AmountDue > 0 ) ,
#OtherBalBccy = #OtherBal * #myrate ,
#PrincipalArrears = dbo.GetPrinArrBF(#AgreementAno , #ProcDate ) , #PrincipalArrearsBccy = #PrincipalArrears * #MyRate ,
#InterestArrears = (Select case when Sum(AmountDue-AmountPaid) is null then 0 else Sum(AmountDue-AmountPaid) end Amount from Trans_Bill where AgreementNo = #AgreementAno and DateDue < = #ProcDate
and ItemCode = '11' and Item not like '%default%' and (ReAccrual = 0 or ReAccrual = 1) ) ,
#InterestArrearsBccy = ( #InterestArrears * #MyRate ) ,
#OtherArrears = (Select case when Sum(AmountDue-AmountPaid) is null then 0 else Sum(AmountDue-AmountPaid) end Amount from Trans_Bill where AgreementNo = #AgreementAno and DateDue < = #procdate and ItemCode NOT in('10','11','19') and AmountDue > 0 ),
#OtherArrearsBccy = #OtherArrears * #myrate ,
#ArrearsInterest = ( Select case when Sum(AmountDue-AmountPaid) is null then 0 else Sum(AmountDue-AmountPaid) end Amount from Trans_Bill where AgreementNo = #AgreementAno and DateDue < = #procdate and ItemCode = '11' and
Item like '%Default%' ) ,
#ArrearsInterestBccy = #ArrearsInterest * #MyRate ,
#PrinArrearsNotdue = 0 , #PrinArrearsNotdueBccy = 0 , #MoOut = 0,
#DaysInArr = dbo.NoOfArrs(#AgreementAno,#ProcDate),
#chargesSp = (Select case when Sum(AmountDue-AmountPaid) is null then 0 else Sum(AmountDue-AmountPaid) end Amount from Trans_Bill where AgreementNo = #AgreementAno and DateDue < = #procdate and ItemCode in(Select chargesCode from charges where affectsincome = 0) and AmountDue > 0 )
select #nextduedate = isnull(#nextduedate,(select TOP 1 datedue from schedules where agreementno = #AgreementAno and processed = 0 ))
select #BaldateRep = #nextduedate
if #InterestArrears < 0
begin
select #InterestArrears = 0
select #InterestArrearsBccy = #InterestArrears * #MyRate
end
end
else
begin
-- select #PrincipalBal = #ApprovedAmount, #PrincipalBalBccy = #ApprovedAmount , #InterestBal = 0 ,
-- #TrustBal = 0 , #TrustBalBccy = 0 , #OtherBal = 0 , #OtherBalBccy = 0 , #PrincipalArrears = 0 ,
-- #PrincipalArrearsBccy = 0 , #InterestArrears = 0 , #InterestArrearsBccy = 0 , #OtherArrears = 0 ,
-- #OtherArrearsBccy = 0 , #ArrearsInterest = 0 , #ArrearsInterestBccy = 0 , #MoOut = 0 ,
-- #PrinArrearsNotdue = 0 , #PrinArrearsNotdueBccy = 0 , #LastCreditDate = '1900-01-01' , #NoOFArr = 0 ,
-- #NoOfArrReal = 0 , #BaldateRep = '1900-01-01' , #DaysInArr = 0
-- end
-- INSERT INTO LhTransBalancePF
-- (
-- BalDate, Currency, ExchangeRate, BaseNo, AgreementNo, Names, PostDate, Tranche , StartDate ,
-- FirstInstaldate , MaturityDate, Term, ApprovedAmount , PaymentFrequency , Rental ,
-- LastPaymentDate , NoOfArrears, ProdCode, ProdName , DaysInArrears, PrincipalBal ,
-- PrincipalBalBccy , InterestBal, InterestBalBccy , TrustBal , TrustBalBccy, OtherBal, OtherBalBccy ,
-- PrincipalArrears , PrincipalArrearsBccy , InterestArrears , InterestArrearsBccy , OtherArrears ,
-- OtherArrearsBccy, ArrearsInterest, ArrearsInterestBccy, MoOutstanding, PostingUser,LastAccrualdate ,
-- IntRate,PricipalArrearsNotDue,PrincipalArrNotDueBccy,NoOfArrearsReal
-- )
-- VALUES
-- (
-- ISNULL(#BalDate,'1900-01-01') ,ISNULL(#MyCurrency,'') ,ISNULL(#MyRate,1) ,ISNULL(#Cno,'') , ISNULL(#AgreementAno,'') ,ISNULL(#Names,'') , ISNULL(#Baldate,'1900-01-01') , ISNULL(#Tranch,0) , ISNULL(#StartDate,'1900-01-01') ,
-- ISNULL(#FirstInstaldate,'1900-01-01') , ISNULL(#MaturityDate,'1900-01-01') , ISNULL(#Term,0) , ISNULL(#ApprovedAmount,0) ,3 ,iif(#Rental=null,0,#Rental) ,
-- #LastCreditDate , ISNULL(#NoOFArr,0) , '' , '' , ISNULL(#DaysInArr,0) , ISNULL(#PrincipalBal,0) ,
-- ISNULL(#PrincipalBalBccy,0) , ISNULL(#InterestBal,0) , ISNULL(#InterestBalBccy,0) , ISNULL(#TrustBal,0) ,ISNULL(#TrustBalBccy,0) ,ISNULL(#OtherBal,0), ISNULL(#OtherBalBccy,0) ,
-- ISNULL(#PrincipalArrears,0) , ISNULL(#PrincipalArrearsBccy,0) , ISNULL(#InterestArrears,0) , ISNULL(#InterestArrearsBccy,0) , ISNULL(#OtherArrears,0) ,
-- ISNULL(#OtherArrearsBccy,0) , ISNULL(#ArrearsInterest,0) , ISNULL(#ArrearsInterestBccy,0) , ISNULL(#MoOut,0) , 'SYSTEM',ISNULL(#BaldateRep,'1900-01-01') ,
-- ISNULL(#intRate,0),ISNULL(#PrinArrearsNotdue,0) ,ISNULL(#PrinArrearsNotdueBccy,0) ,ISNULL( #NoOfArrReal ,0)
-- )
--update LHTransBalancePF set Registered = #Registered, RegisteredCollateral = #RegisteredCollateral,
--ProdCode = #ProdCode ,loansizecategory = case when ApprovedAmount < = 5000000 then 'SMALL'
--WHEN ApprovedAmount > 5000000 and ApprovedAmount < = 30000000 then 'MEDIUM'
--ELSE 'LARGE' END
--WHERE AgreementNo = #AgreementAno AND LhTransBalancePF.Baldate = #Baldate
--UPDATE LhTransBalancePF SET ProdName = Product.ProductName FROM LhTransBalancePF INNER JOIN Product
--ON LhTransBalancePF.ProdCode = Product.ProductCode
--WHERE AgreementNo = #AgreementAno AND BalDate = #Baldate
select #PrincipalBal = #ApprovedAmount, #PrincipalBalBccy = #ApprovedAmount , #InterestBal = 0 ,
#TrustBal = 0 , #TrustBalBccy = 0 , #OtherBal = 0 , #OtherBalBccy = 0 , #PrincipalArrears = 0 ,
#PrincipalArrearsBccy = 0 , #InterestArrears = 0 , #InterestArrearsBccy = 0 , #OtherArrears = 0 ,
#OtherArrearsBccy = 0 , #ArrearsInterest = 0 , #ArrearsInterestBccy = 0 , #MoOut = 0 ,
#PrinArrearsNotdue = 0 , #PrinArrearsNotdueBccy = 0 , #LastCreditDate = '1900-01-01' , #NoOFArr = 0 ,
#NoOfArrReal = 0 , #BaldateRep = '1900-01-01' , #DaysInArr = 0,#chargesSp =0
end
INSERT INTO LhTransBalance
(
BalDate, Currency, ExchangeRate, BaseNo, AgreementNo, Names, PostDate, Tranche , StartDate ,
FirstInstaldate , MaturityDate, Term, ApprovedAmount , PaymentFrequency , Rental ,
LastPaymentDate , NoOfArrears, ProdCode, ProdName , DaysInArrears, PrincipalBal ,
PrincipalBalBccy , InterestBal, InterestBalBccy , TrustBal , TrustBalBccy, OtherBal, OtherBalBccy ,
PrincipalArrears , PrincipalArrearsBccy , InterestArrears , InterestArrearsBccy , OtherArrears ,
OtherArrearsBccy, ArrearsInterest, ArrearsInterestBccy, MoOutstanding, PostingUser,LastAccrualdate ,
IntRate,PricipalArrearsNotDue,PrincipalArrNotDueBccy,NoOfArrearsReal, ChargesArrearsSp
)
VALUES
(
ISNULL(#BalDate,'1900-01-01') ,ISNULL(#MyCurrency,'') ,ISNULL(#MyRate,1) ,ISNULL(#Cno,'') , ISNULL(#AgreementAno,'') ,ISNULL(#Names,'') , ISNULL(#Baldate,'1900-01-01') , ISNULL(#Tranch,0) , ISNULL(#StartDate,'1900-01-01') ,
ISNULL(#FirstInstaldate,'1900-01-01') , ISNULL(#MaturityDate,'1900-01-01') , ISNULL(#Term,0) , ISNULL(#ApprovedAmount,0) ,3 ,iif(#Rental=null,0,#Rental) ,
#LastCreditDate , ISNULL(#NoOFArr,0) , '' , '' , ISNULL(#DaysInArr,0) , ISNULL(#PrincipalBal,0) ,
ISNULL(#PrincipalBalBccy,0) , ISNULL(#InterestBal,0) , ISNULL(#InterestBalBccy,0) , ISNULL(#TrustBal,0) ,ISNULL(#TrustBalBccy,0) ,ISNULL(#OtherBal,0), ISNULL(#OtherBalBccy,0) ,
ISNULL(#PrincipalArrears,0) , ISNULL(#PrincipalArrearsBccy,0) , ISNULL(#InterestArrears,0) , ISNULL(#InterestArrearsBccy,0) , ISNULL(#OtherArrears,0) ,
ISNULL(#OtherArrearsBccy,0) , ISNULL(#ArrearsInterest,0) , ISNULL(#ArrearsInterestBccy,0) , ISNULL(#MoOut,0) , 'SYSTEM',ISNULL(#BaldateRep,'1900-01-01') ,
ISNULL(#intRate,0),ISNULL(#PrinArrearsNotdue,0) ,ISNULL(#PrinArrearsNotdueBccy,0) ,ISNULL( #NoOfArrReal ,0) ,ISNULL( #chargesSp ,0)
)
update LHTransBalance set Registered = #Registered, RegisteredCollateral = #RegisteredCollateral,
ProdCode = #ProdCode ,loansizecategory = case when ApprovedAmount < = 5000000 then 'SMALL'
WHEN ApprovedAmount > 5000000 and ApprovedAmount < = 30000000 then 'MEDIUM'
ELSE 'LARGE' END
WHERE AgreementNo = #AgreementAno AND LhTransBalance.Baldate = #Baldate
--NO' 2017-09-19
update LhTransBalance set OldAno= pfagreements.oldagreementno, residualvalue = pfagreements.residualValue
from pfagreements inner join lhtransbalance on pfagreements.agreementno= LhTransBalance.agreementno
WHERE lhtransbalance.AgreementNo = #AgreementAno AND LhTransBalance.Baldate = #Baldate
--End
UPDATE LhTransBalance SET ProdName = Product.ProductName FROM LhTransBalance INNER JOIN Product
ON LhTransBalance.ProdCode = Product.ProductCode
WHERE AgreementNo = #AgreementAno AND BalDate = #Baldate
Fetch next from curAgreement1 into #AgreementAno
end
close curAgreement1
deallocate curAgreement1
Thank you for your help

Two multi-value parameters in SSRS

I have two multi-value parameters in my SQL: where (PayToTIN IN (#PayToTIN) or PCP_ProvId IN (#PCP_ProvId). I am trying to drop in multiple values in either or parameters however when I drop in a value in either parameter, SSRS treats the other parameter as ''. I am also unable to null out the either param because they are multi-value. Is there a workaround to run multiple values in either one or the other parameter?
Declare #PayToTIN as varchar(max) = '562660402' --'562660402'
Declare #PCP_ProvId as varchar(max) --= 'LASRL12550' --'LASRL12550'
declare #detailfields as varchar(max) = NULL
declare #PayToTIN_switch varchar(max) =
( select max(PayToTIN)
from LA_Temp.dbo.vMemberPCP
where cast(PayToTIN as varchar) in (#PayToTIN)
)
declare #PCPAssignmentID_switch varchar(max) =
( select max(PCP_ProvId)
from LA_Temp.dbo.vMemberPCP
where cast(PCP_ProvId as varchar) in (#PCP_ProvId)
)
declare #include_PayToTIN bit = case when 'Pay To Tin' in (#detailfields) then 1 else 0 end
declare #include_PCP_ProvId bit = case when 'PCP ProvID' in (#detailfields) then 1 else 0 end
select distinct
x.CarrierMemID
-- , MemberName
, MbrLastName =rtrim( e.LastName)
, MbrFirstName = rtrim(e.FirstName)
, MbrMI = rtrim(e.MiddleName)
, x.DOB
, x.Age
, x.Sex
, Address = e.addr1
, City = e.city
, State = e.state
, Zip = e.zip
, Parish = e.county
, MemPhone = e.phone
, PCPName
, PCP_NPI
, PCPProvID
, PCPEffDate
, Specialty
, ServiceLocation
, PayToProvider
, PayToTIN
, PayToProvID
, PCP_ProvId
, PCPAssignment
from LA_Temp.dbo.vMemberPCP x
inner join PlanReport_QNXT_LA.dbo.enrollkeys ek
on x.enrollid = ek.enrollid
inner join PlanReport_QNXT_LA.dbo.orgpolicy o
on o.orgpolicyid = ek.orgpolicyid
and right(rtrim(o.policynum),2) <> 'BH'
inner join PlanReport_QNXT_LA.dbo.member m
on ek.memid = m.memid
inner join PlanReport_QNXT_LA.dbo.entity e
on e.entid = m.entityid
--where PayToTIN = #PayToTIN --AMB 05/07/18
where (PayToTIN IN (#PayToTIN)
or '' = #PayToTIN_switch
)
or ( PCP_ProvId IN (#PCP_ProvId)
or '' = #PCPAssignmentID_switch
)
where (case when PayToTIN = '' then null else PayToTIN end in (#PayToTIN))
OR (case when PCP_ProvId = '' then null else PCP_ProvId end in (#PCP_ProvId))

Is it possible to Pivot this query?

My query
SELECT DISTINCT dbo.tblacc_cv.cv_docno,
dbo.tblacc_cv.cv_docdate,
dbo.tblacc_cv.cv_suppliername,
dbo.tblacc_cv.cv_extdocno,
dbo.tblacc_chartaccount.coa_cvtype AS cvtype,
dbo.tblacc_glentry.gl_accountid,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid = '201001' THEN Sum(
dbo.tblacc_glentry.gl_credit)
ELSE NULL
END ) AS AP,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid = '208000' THEN Sum(
dbo.tblacc_glentry.gl_amount)
ELSE NULL
END ) AS EWT,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid = '616000'
AND dbo.tblacc_chartaccount.coa_cvtype = 'S' THEN Sum(
dbo.tblacc_glentry.gl_debit)
ELSE NULL
END ) AS FABpur,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid = '603000'
AND dbo.tblacc_chartaccount.coa_cvtype = 'S' THEN Sum(
dbo.tblacc_glentry.gl_debit)
ELSE NULL
END ) AS FABcre,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid = '602000'
AND dbo.tblacc_chartaccount.coa_cvtype = 'S' THEN Sum(
dbo.tblacc_glentry.gl_debit)
ELSE NULL
END ) AS RawMat,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid = '601003'
AND dbo.tblacc_chartaccount.coa_cvtype = 'S' THEN Sum(
dbo.tblacc_glentry.gl_debit)
ELSE NULL
END ) AS PurCre,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid NOT IN (
'201001', '208000', '616000', '603000',
'602000', '601003' ) THEN
dbo.tblacc_glentry.gl_accountname
ELSE NULL
END ) AS GL_AccountName,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid NOT IN (
'616000', '603000', '602000', '601003'
)
AND dbo.tblacc_chartaccount.coa_cvtype = 'M' THEN Sum(
dbo.tblacc_glentry.gl_debit)
ELSE NULL
END ) AS MOdr,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid NOT IN (
'616000', '603000', '602000', '601003'
)
AND dbo.tblacc_chartaccount.coa_cvtype = 'F' THEN Sum(
dbo.tblacc_glentry.gl_debit)
ELSE NULL
END ) AS FDR,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid NOT IN (
'201001', '208000', '616000', '603000',
'602000', '601003' )
AND dbo.tblacc_chartaccount.coa_cvtype = 'S' THEN Sum(
dbo.tblacc_glentry.gl_debit)
ELSE NULL
END ) AS SunDR,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid NOT IN (
'201001', '208000', '616000', '603000',
'602000', '601003' )
AND dbo.tblacc_chartaccount.coa_cvtype = 'S' THEN Sum(
dbo.tblacc_glentry.gl_credit)
ELSE NULL
END ) AS SunCR
FROM dbo.tblacc_glentry
INNER JOIN dbo.tblacc_apv
ON dbo.tblacc_glentry.gl_docno = dbo.tblacc_apv.apv_docno
INNER JOIN dbo.tblacc_cv
INNER JOIN dbo.tblacc_cvdetail
ON dbo.tblacc_cv.cv_docno =
dbo.tblacc_cvdetail.cvd_cv_docno
ON dbo.tblacc_apv.apv_docno = dbo.tblacc_cvdetail.cvd_refdocno
INNER JOIN dbo.tblacc_chartaccount
ON dbo.tblacc_glentry.gl_accountid =
dbo.tblacc_chartaccount.coa_account_id
WHERE ( dbo.tblacc_cv.cv_docdate BETWEEN
'01/01/2018 00:00:00' AND '1/30/2018 23:59:59' )
GROUP BY dbo.tblacc_cv.cv_docno,
dbo.tblacc_cv.cv_docdate,
dbo.tblacc_cv.cv_suppliername,
dbo.tblacc_glentry.gl_accountname,
dbo.tblacc_cv.cv_extdocno,
dbo.tblacc_chartaccount.coa_cvtype,
dbo.tblacc_glentry.gl_accountid,
dbo.tblacc_glentry.gl_credit,
dbo.tblacc_glentry.gl_amount,
dbo.tblacc_glentry.gl_debit
ORDER BY dbo.tblacc_cv.cv_docdate ASC
Sample Output
Desired Ouput
Your desired output is not an example of a PIVOT.
Lacking a detailed explanation of your logic, I can tell you that you can get your desired output by GROUPing BY the first four columns, and applying MAX() to all the others. (Except cvtype which would be a MIN).

Removing duplicates from select query output

Could anyone please suggest what is the error in the below query? Actually I want to remove all duplicates from the select query output and fetch only unique rows. Thanks in advance.
select *
from (
select ROW_NUMBER() over (
partition by Dep
, tariffkode
, LinkTariffType
, poliata
, poliatavia
, podiata
, podiatavia
, PreCarriage
, PortTerminalId
, Product
, RoutingOrder
, PrepaidCollect
, isnull(description, '')
, ScaleCalcCode
, isnull(scalefrom, 0)
, isnull(scaleto, 0)
, CurrencyCode
, Base order by LinkTariffType desc
) Record
, *
from (
select tn.LinkTariffType
, tn.Dep
, tn.POLIata
, tn.POLIatavia
, tn.PODIata
, tn.PODIatavia
, tn.CurrencyCode
, tn.LegalEntityID
, tn.Rate
, tn.Base
, tn.Minimum
, tn.NrDescription
, tn.Description
, tn.DateFrom
, tn.DateUntil
, tn.DateCreate
, tn.DateMod
, tn.ModName
, tn.Tariffkode
, tn.ExpiryDate
, tn.PClass
, tn.Maximum
, tn.RoutingOrder
, tn.TariffCompType
, tn.PrePaidCollect
, tn.Product
, tn.IsDeleted
, (
select distinct Location_IATA
from Company
where Called = 'KARL KING'
and LegalEntityID = 1
and IsDeleted = 0
) as PreCarriage
, tn.PortTerminalID
, tn.ScaleFrom
, tn.ScaleTo
, tn.ScaleCalcCode
, tn.Mandatory
, (
select CompanyID
from PlaceOfReceipt
where warehouse = 'KARL KING'
and LegalEntityID = 1
and OfficeID = 13
and IsDeleted = 0
) as WarehouseID
, tn.TariffRelID
, tn.FreeDescription
, 0
, tn.ShipCode
, tn.AgentID
, tn.ContainerTypeID
, tn.CommodityID
, 0 as TempTable
from TariffNew tn
inner join hhInvoiceLines inv
on tn.Tariffkode = inv.NrInvoiceLine
where (
tn.PreCarriage is not null
and tn.PreCarriage != ''
)
and (
tn.POLIata is not null
and tn.POLIata != ''
)
and inv.OfficeID = 13
and inv.IsDeleted = 0
and inv.LegalEntityID = 1
and tn.LegalEntityID = 1
and tn.Dep = 'E'
and tn.IsDeleted = 0
and tn.DateUntil = '2078-12-31 00:00:00'
and tn.Description = 'kgl'
)
) as b
where b.Record = 1
First, you have to define what you want to call "unique rows".
Once you have the set of columns that determines a row is unique, that is the set of columns you use in the partition by part of row_number()
In the code below, uncomment the column set that defines your "unique rows":
select *
from (
select ROW_NUMBER() over (
partition by
Dep
--, tariffkode
--, LinkTariffType
--, poliata
--, poliatavia
--, podiata
--, podiatavia
--, PreCarriage
--, PortTerminalId
--, Product
--, RoutingOrder
--, PrepaidCollect
--, isnull(description, '')
--, ScaleCalcCode
--, isnull(scalefrom, 0)
--, isnull(scaleto, 0)
--, CurrencyCode
--, Base
order by LinkTariffType desc
) Record
, *
from (
select tn.LinkTariffType
, tn.Dep
, tn.POLIata
, tn.POLIatavia
, tn.PODIata
, tn.PODIatavia
, tn.CurrencyCode
, tn.LegalEntityID
, tn.Rate
, tn.Base
, tn.Minimum
, tn.NrDescription
, tn.Description
, tn.DateFrom
, tn.DateUntil
, tn.DateCreate
, tn.DateMod
, tn.ModName
, tn.Tariffkode
, tn.ExpiryDate
, tn.PClass
, tn.Maximum
, tn.RoutingOrder
, tn.TariffCompType
, tn.PrePaidCollect
, tn.Product
, tn.IsDeleted
, (
select distinct Location_IATA
from Company
where Called = 'KARL KING'
and LegalEntityID = 1
and IsDeleted = 0
) as PreCarriage
, tn.PortTerminalID
, tn.ScaleFrom
, tn.ScaleTo
, tn.ScaleCalcCode
, tn.Mandatory
, (
select CompanyID
from PlaceOfReceipt
where warehouse = 'KARL KING'
and LegalEntityID = 1
and OfficeID = 13
and IsDeleted = 0
) as WarehouseID
, tn.TariffRelID
, tn.FreeDescription
, 0 as UnnamedColumn
, tn.ShipCode
, tn.AgentID
, tn.ContainerTypeID
, tn.CommodityID
, 0 as TempTable
from TariffNew tn
inner join hhInvoiceLines inv on tn.Tariffkode = inv.NrInvoiceLine
where tn.PreCarriage is not null
and tn.PreCarriage != ''
and tn.POLIata is not null
and tn.POLIata != ''
and inv.OfficeID = 13
and inv.IsDeleted = 0
and inv.LegalEntityID = 1
and tn.LegalEntityID = 1
and tn.Dep = 'E'
and tn.IsDeleted = 0
and tn.DateUntil = '2078-12-31 00:00:00'
and tn.Description = 'kgl'
) as s
) as b
where b.Record = 1

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.