sqlite query to get earliest date - sql

I have the following query:
SELECT (CASE WHEN cc.id IS NULL THEN dc.id ELSE cc.id END) AS id,
l.CALL,l.QSO_DATE,cc.prefix,l.state,l.QSL_RCVD,l.Band,l.Mode,
(CASE WHEN CC.Country IS NULL THEN dc.Country ELSE cc.Country END) AS country,
(CASE WHEN CC.Country IS NULL THEN 'Y' ELSE 'N' END) AS 'deleted',
(CASE WHEN CC.flags IS NULL THEN dc.flags ELSE cc.flags END) AS 'flag'
FROM lotw l
LEFT OUTER JOIN CountryCode AS cc on cc.code = l.dxcc
LEFT OUTER JOIN DeleteCountry AS dc on dc.code = l.dxcc
WHERE l.DXCC > ''
GROUP BY CC.Country,dc.Country ORDER BY cc.COUNTRY,dc.COUNTRY.
which returns a set of unique country that matches the countrycode table code field.
the speed is good less than a second.
I needed to expand this so the query select's the earliest QSLRDATE from the LOTW table.
so I modify the query like this:
SELECT (CASE WHEN cc.id IS NULL THEN dc.id ELSE cc.id END) AS id, l.CALL,l.QSO_DATE,cc.prefix,l.state,l.QSL_RCVD,l.Band,l.Mode,
(CASE WHEN CC.Country IS NULL THEN dc.Country ELSE cc.Country END) AS country,
(CASE WHEN CC.Country IS NULL THEN 'Y' ELSE 'N' END) AS 'deleted',
(CASE WHEN CC.flags IS NULL THEN dc.flags ELSE cc.flags END) AS 'flag'
FROM lotw l
LEFT OUTER JOIN CountryCode AS cc on cc.code = l.dxcc
LEFT OUTER JOIN DeleteCountry AS dc on dc.code = l.dxcc
WHERE l.QSLRDATE = (SELECT MIN(l2.QSLRDATE) FROM LOTW l2 WHERE l2.DXCC=l.DXCC) AND l.DXCC > ''
GROUP BY CC.Country,dc.Country ORDER BY cc.COUNTRY,dc.COUNTRY
this works but the performance went from less than a second to 15 seconds.
The sub query I added:
l.QSLRDATE = (SELECT MIN(l2.QSLRDATE) FROM LOTW l2 WHERE l2.DXCC=l.DXCC)
can't be the best way to accomplish what I want.
any help would be great.

Try joining on a sub-query rather than using a correlated sub-query in the WHERE clause.
SELECT
(CASE WHEN cc.id IS NULL THEN dc.id ELSE cc.id END) AS id,
l.CALL,l.QSO_DATE,cc.prefix,l.state,l.QSL_RCVD,l.Band,l.Mode,
(CASE WHEN CC.Country IS NULL THEN dc.Country ELSE cc.Country END) AS country,
(CASE WHEN CC.Country IS NULL THEN 'Y' ELSE 'N' END) AS 'deleted',
(CASE WHEN CC.flags IS NULL THEN dc.flags ELSE cc.flags END) AS 'flag'
FROM
(SELECT dxcc, MIN(qslrdate) AS qslrdate FROM lotw GROUP BY dxcc) AS qslr
INNER JOIN lotw AS l ON l.dxcc = qslr.dxcc AND l.qslrdate = qslr.qslrdate
LEFT OUTER JOIN CountryCode AS cc on cc.code = l.dxcc
LEFT OUTER JOIN DeleteCountry AS dc on dc.code = l.dxcc
WHERE l.DXCC > ''
GROUP BY CC.Country,dc.Country ORDER BY cc.COUNTRY,dc.COUNTRY
Also, make sure that lotw has an index on (dxcc, qslrdate) to make ensure both the sub-query and join perform well.
Infact, ensure you have that index first, and retry your query. Then, if the performance is still poor, try the above query.

Related

How to sum up the cursor value and store the value in another select statement in the same procedure?

I have two tables, one is general table and another is loan table.
General table includes id and name and id is not repeating.
Loan table includes id and loan amount. In loan table, the id may be repeating as one customer can have multiple loans.
Idea is to create a procedure which will join this both the table on the basis of id and display the final table with id, name and sum of all loans for that particular id (must sum up the value of common id's and store in single column) with the help of cursor.
Can only use procedure and cursor.
If it can be solved without cursor, then please provide the alternate solution.
I am using below query for the same, but unfortunately the end result displays the id multiple times:
SELECT
A.bpm_referenceno,
CASE WHEN B.loanbookingbranch='--Select--' or B.loanbookingbranch='null' THEN '' ELSE B.loanbookingbranch END,
CASE WHEN A.branch='' OR A.branch IS NULL OR A.branch='null' THEN '' ELSE A.branch END,
'',
CASE WHEN A.originator='' OR A.originator IS NULL OR A.originator='null' THEN '' ELSE A.originator END,
A.cif_id,
CASE WHEN D.callexecutiondate='' OR D.callexecutiondate IS NULL OR D.callexecutiondate ='null' THEN '' ELSE CASE WHEN D.calldescription='MG Contract Creation' AND D.callstatus='SUCCESS' THEN D.callexecutiondate END END,
CASE WHEN A.originationdate IS NULL THEN '' ELSE A.originationdate END,
CASE WHEN A.request_type='' OR A.request_type IS NULL OR A.request_type='null' THEN '' ELSE A.request_type END,
CASE WHEN a.loan_subtype='' OR a.loan_subtype IS NULL OR a.loan_subtype='null' THEN '' ELSE a.loan_subtype END,
CASE WHEN E.loanamounttxndetails IS NULL OR E.loanamounttxndetails ='null' OR E.loanamounttxndetails='' THEN '0' ELSE e.loanamounttxndetails END,
CASE WHEN E.customerdbrtxndetails IS NULL OR E.customerdbrtxndetails ='null' OR E.customerdbrtxndetails='' THEN '0.00' ELSE E.customerdbrtxndetails END,
'stlment count',
'loan os',
--Here I am inserting the query--
(SELECT
isnull(ab.mycount,0)
FROM
bm_rlos_exttable aa
LEFT OUTER JOIN
(SELECT bpm_referenceno,count(bpm_referenceno) mycount FROM
BM_RLOS_ExistingBMLiabilitiesGrid GROUP BY bpm_referenceno) ab ON aa.bpm_referenceno = ab.bpm_referenceno),
CASE WHEN G.isselected='true' THEN G.insuranceType ELSE '' END,
CASE WHEN E.loantenortxndetails IS NULL OR E.loantenortxndetails='' OR E.loantenortxndetails='null' THEN '' ELSE E.loantenortxndetails END,
CASE WHEN E.interestratetxndetails IS NULL OR E.interestratetxndetails='' OR E.interestratetxndetails='null' THEN '' ELSE E.interestratetxndetails END,
'CHARGE1',
'CHARGE2',
CASE WHEN D.calldescription='MG Contract Creation' AND D.callstatus='SUCCESS' THEN D.callreferenceid ELSE '' END,
'rco',
'tat'
FROM
BM_RLOS_EXTTABLE A WITH (NOLOCK)
INNER JOIN BM_RLOS_BasicLoanDetailsForm B WITH (NOLOCK)
ON A.bpm_referenceno = B.bpm_referenceno
INNER JOIN BM_RLOS_DisbursementCallsGrid D WITH (NOLOCK)
ON A.bpm_referenceno = D.bpm_referenceno
INNER JOIN BM_RLOS_CheckFinalEligibilityForm E WITH (NOLOCK)
ON A.bpm_referenceno = E.bpm_referenceno
INNER JOIN BM_RLOS_ExistingBMLiabilitiesGrid F WITH (NOLOCK)
ON A.bpm_referenceno = F.bpm_referenceno
INNER JOIN BM_RLOS_InsuranceProductSelectionGrid G WITH (NOLOCK)
ON A.bpm_referenceno = G.bpm_referenceno
INNER JOIN BM_RLOS_ChargeAndFeeDetailsForm H WITH (NOLOCK)
ON A.bpm_referenceno = H.bpm_referenceno
INNER JOIN BM_RLOS_DecisionHistoryForm I WITH (NOLOCK)
ON A.bpm_referenceno = I.bpm_referenceno
INNER JOIN wfcurrentroutelogtable J WITH (NOLOCK)
ON A.bpm_referenceno = J.ProcessInstanceId
This should do the trick
SELECT
a.id,
a.name,
b.mysum
FROM
General_Table a
LEFT OUTER JOIN (select bpm_id, SUM(outstandingamount) mysum
from loan_table group by bpm_id) b
ON a.id = b.bpm_id
Edit: subquery changed ( based on your join clause i assumed your id field in the loan_table was bpm_id)
Edit2:
Note i moved your nested query into a new LEFT JOIN in order to make this work.
You cannot use nested query in a select statement if it returns more then 1 record
SELECT
A.bpm_referenceno,
CASE WHEN B.loanbookingbranch='--Select--' or B.loanbookingbranch='null' THEN '' ELSE B.loanbookingbranch END,
CASE WHEN A.branch='' OR A.branch IS NULL OR A.branch='null' THEN '' ELSE A.branch END,
'',
CASE WHEN A.originator='' OR A.originator IS NULL OR A.originator='null' THEN '' ELSE A.originator END,
A.cif_id,
CASE WHEN D.callexecutiondate='' OR D.callexecutiondate IS NULL OR D.callexecutiondate ='null' THEN '' ELSE CASE WHEN D.calldescription='MG Contract Creation' AND D.callstatus='SUCCESS' THEN D.callexecutiondate END END,
CASE WHEN A.originationdate IS NULL THEN '' ELSE A.originationdate END,
CASE WHEN A.request_type='' OR A.request_type IS NULL OR A.request_type='null' THEN '' ELSE A.request_type END,
CASE WHEN a.loan_subtype='' OR a.loan_subtype IS NULL OR a.loan_subtype='null' THEN '' ELSE a.loan_subtype END,
CASE WHEN E.loanamounttxndetails IS NULL OR E.loanamounttxndetails ='null' OR E.loanamounttxndetails='' THEN '0' ELSE e.loanamounttxndetails END,
CASE WHEN E.customerdbrtxndetails IS NULL OR E.customerdbrtxndetails ='null' OR E.customerdbrtxndetails='' THEN '0.00' ELSE E.customerdbrtxndetails END,
'stlment count',
'loan os',
--Here I am inserting the query--
mycount,
CASE WHEN G.isselected='true' THEN G.insuranceType ELSE '' END,
CASE WHEN E.loantenortxndetails IS NULL OR E.loantenortxndetails='' OR E.loantenortxndetails='null' THEN '' ELSE E.loantenortxndetails END,
CASE WHEN E.interestratetxndetails IS NULL OR E.interestratetxndetails='' OR E.interestratetxndetails='null' THEN '' ELSE E.interestratetxndetails END,
'CHARGE1',
'CHARGE2',
CASE WHEN D.calldescription='MG Contract Creation' AND D.callstatus='SUCCESS' THEN D.callreferenceid ELSE '' END,
'rco',
'tat'
FROM
BM_RLOS_EXTTABLE A WITH (NOLOCK)
INNER JOIN BM_RLOS_BasicLoanDetailsForm B WITH (NOLOCK)
ON A.bpm_referenceno = B.bpm_referenceno
INNER JOIN BM_RLOS_DisbursementCallsGrid D WITH (NOLOCK)
ON A.bpm_referenceno = D.bpm_referenceno
INNER JOIN BM_RLOS_CheckFinalEligibilityForm E WITH (NOLOCK)
ON A.bpm_referenceno = E.bpm_referenceno
INNER JOIN BM_RLOS_ExistingBMLiabilitiesGrid F WITH (NOLOCK)
ON A.bpm_referenceno = F.bpm_referenceno
INNER JOIN BM_RLOS_InsuranceProductSelectionGrid G WITH (NOLOCK)
ON A.bpm_referenceno = G.bpm_referenceno
INNER JOIN BM_RLOS_ChargeAndFeeDetailsForm H WITH (NOLOCK)
ON A.bpm_referenceno = H.bpm_referenceno
INNER JOIN BM_RLOS_DecisionHistoryForm I WITH (NOLOCK)
ON A.bpm_referenceno = I.bpm_referenceno
INNER JOIN wfcurrentroutelogtable J WITH (NOLOCK)
ON A.bpm_referenceno = J.ProcessInstanceId
left join
(SELECT bpm_referenceno,count(bpm_referenceno) mycount FROM
BM_RLOS_ExistingBMLiabilitiesGrid GROUP BY bpm_referenceno) ab ON ab.bpm_referenceno = a.bpm_referenceno)
You don't need cursor at all! It's inefficient. This can be done simply by JOINing and GROUPing. Try this query:
select g.id, l.totalLoan from GeneralTable [g]
join (
select id, sum(loan) [totalLoan] from LoanTable
group by id
) [l] on [g].id = [l].id

Complex Case Statement Issue - Oracle SQL

Wrote the query below, but am getting multiplied amounts because the aggregation needs to occur before the case statements. Would love some advice on the best way to structure this.
Select Store, CUSTID, CUST.ID_CUST,
Sum(
CASE
WHEN Cust_Gift.Code_Status = 'C' AND Gift_Item.FLAG_STORE_LOC = 'N'
THEN Cust_Gift.AMT_PAID ELSE 0
END) GiftAmt,
Sum(
CASE WHEN Cust_Gift.Code_Status = 'C' AND Gift_Item.FLAG_STORE_LOC = 'Y'
THEN Cust_Gift.AMT ELSE 0
END) CustGiftAmt,
Sum(
CASE WHEN Cust_Coupon.Code_Status = 'C'
THEN Cust_Coupon.AMT
ELSE 0
END) CouponAmt,
Sum(CASE WHEN Cust_Sports.Status = 'C'
THEN Cust_Sports.AMT
ELSE 0
END) SportsAmt
FROM CUST
LEFT OUTER JOIN CUST_GIFT
ON CUST.ID_CUST = CUST_GIFT.ID_CUST
LEFT OUTER JOIN CUST_COUPON
ON CUST.ID_CUST = CUST_COUPON.ID_CUST
LEFT OUTER JOIN CUST_SPORTS
ON CUST.ID_CUST = CUST_SPORTS.ID_CUST
INNER JOIN GIFT_ITEM
ON CUST_GIFT.ID_GIFT_ITEM = GIFT_ITEM.ID_GIFT_ITEM
WHERE (STORE = 'M669098' OR STORE = 'M66923434' )
Group by CustID, Store, CUST.ID_CUST
This is one way you could do it:
SELECT cust.store,
cust.custid,
cust.id_cust,
gift.giftamt,
gift.custgift,
cpn.couponamt,
sprt.sportsamt
FROM cust
LEFT OUTER JOIN (SELECT id_cust,
SUM(CASE WHEN cg.code_status = 'C' AND gi.flag_store_loc = 'N' THEN cg.amt_paid END) giftamt,
SUM(CASE WHEN cg.code_status = 'C' AND gi.flag_store_loc = 'Y' THEN cg.amt_paid END) custgiftamt
FROM cust_gift cg
INNER JOIN gift_item gi ON cg.id_gift_item = gi.id_gift_item) gift ON cust.id_cust = gift.id_cust
LEFT OUTER JOIN (SELECT id_cust,
SUM(CASE WHEN code_status = 'C' THEN amt END) couponamt
FROM cust_coupon) cpn ON cust.id_cust = cpn.id_cust
LEFT OUTER JOIN (SELECT id_cust,
SUM(CASE WHEN status = 'C' THEN amt END) sportsamt
FROM cust_sports) sprt ON cust.id_cust = sprt.id_cust
WHERE (STORE = 'M669098' OR STORE = 'M66923434');

SQL Server 2012 - is there a better way to do this as when there are duplicates it counts them more than once?

This is not accurate as the count can be wrong so is there a better way using exists? I want to identify if one case of each course exists.
SELECT
IdentityCourses.IdentityID AS ID,Identities.LastName AS LastName,
Identities.FirstNames AS FirstName,Units.UnitID, Units.Description AS Unit
FROM
dbo.UnitIdentities
INNER JOIN
dbo.IdentityCourses ON dbo.UnitIdentities.IdentityID = dbo.IdentityCourses.IdentityID
INNER JOIN
dbo.COCSourceCourses ON dbo.IdentityCourses.CourseID = dbo.COCSourceCourses.CBESCourseID
INNER JOIN
dbo.Identities ON dbo.UnitIdentities.IdentityID = dbo.Identities.IdentityID
INNER JOIN
dbo.Units ON dbo.UnitIdentities.UnitID = dbo.Units.UnitID
WHERE
(dbo.UnitIdentities.IsActiveMember = 1)
GROUP BY
IdentityCourses.IdentityID, Identities.LastName, Identities.FirstNames,
Units.Description, Units.UnitID
HAVING
(SUM((CASE WHEN COCSourceCourses.COCID = 10048 then 1 else 0 end)+
(CASE WHEN COCSourceCourses.COCID = 10049 then 1 else 0 end)+
(CASE WHEN COCSourceCourses.COCID = 10050 then 1 else 0 end)+
(CASE WHEN COCSourceCourses.COCID = 10051 then 1 else 0 end)+
(CASE WHEN COCSourceCourses.COCID = 10063 then 1 else 0 end)+
(CASE WHEN COCSourceCourses.COCID = 10073 then 1 else 0 end))) = 6
AND IdentityCourses.IdentityID NOT IN (SELECT IdentityID
FROM IdentityQualifications
WHERE QualificationID IN (1012, 1014, 1025))
ORDER BY
Units.UnitID
Try using count(distinct ..):
SELECT (..columns..)
FROM dbo.UnitIdentities UI
LEFT JOIN IdentityQualifications IQ
ON IQ.IdentityID = UI.IdentityID
AND IQ.QualificationID IN (1012, 1014, 1025)
INNER JOIN dbo.IdentityCourses IC
ON IC.IdentityID = dbo.UnitIdentities.IdentityID
INNER JOIN dbo.COCSourceCourses COC
ON COC.CBESCourseID = IC.CourseID
AND COC.COCID IN (10048, 10049, 10050, 10051, 10063, 10073)
(..two more table joins on identities and units..)
WHERE IQ.IdentityID IS NULL
GROUP BY (..columns..)
HAVING COUNT(DISTINCT COC.COCID) = 6
ORDER BY Units.UnitID
When you are only interested in certain records, then why don't you use the WHERE clause? Only select the COCIDs you are interested in and then count distinct results.
You don't need any GROUP BY and HAVING by the way, as you only display identities/units, so you can count associated courses in a subquery in your WHERE clause.
select
i.identityid as id,
i.lastname as lastname,
i.firstnames as firstname,
u.unitid,
u.description as unit
from dbo.identities i
join dbo.unitidentities ui on ui.identityid = i.identityid and ui.isactivemember = 1
join dbo.units u on u.unitid = ui.unitid
where i.identityid not in
(
select iq.identityid
from identityqualifications iq
where iq.qualificationid in (1012, 1014, 1025)
)
and
(
select count(distinct sc.cocid)
from dbo.cocsourcecourses sc
join dbo.identitycourses ic on ic.courseid = sc.cbescourseid
where sc.cocid in (10048, 10049, 10050, 10051, 10063, 10073)
and ic.identityid = i.identityid
) = 6
order by u.unitid;

SQL QUERY with subquery Optimization

how can i optimize these query
SELECT
mp.ProviderName
,(SELECT count(mc.ClaimSubmissionID) FROM dbo.MST_Claim mc WHERE mc.HeaderID=mpach.HeaderID AND mc.IsActive=1) AS total_claim
,(SELECT count(mc.ClaimSubmissionID) FROM dbo.MST_Claim mc WHERE mc.HeaderID=mpach.HeaderID AND mc.op=1) AS total_op
,(SELECT count(mc.ClaimSubmissionID) FROM dbo.MST_Claim mc WHERE mc.HeaderID=mpach.HeaderID AND mc.ip=1) AS total_ip
FROM dbo.MST_PriorAuthorization_Claim_Header mpach
INNER JOIN dbo.MS_Provider mp ON mp.Provider_ID = mpach.Provider_ID
Use Sum of CASE Statements to avoid all those subqueries.
SELECT
mp.ProviderName,
SUM(CASE WHEN mc.IsActive=1 THEN 1 ELSE 0 END ) AS total_claim,
SUM(CASE WHEN mc.op=1 THEN 1 ELSE 0 END ) AS total_op,
SUM(CASE WHEN mc.ip=1 THEN 1 ELSE 0 END ) AS total_ip
FROM dbo.MST_PriorAuthorization_Claim_Header mpach
INNER JOIN dbo.MS_Provider mp ON mp.Provider_ID = mpach.Provider_ID
INNER JOIN dbo.MST_Claim mc ON mc.HeaderID=mpach.HeaderID
You can modify your query using a CASE statement like below
SELECT
mp.ProviderName
,sum(case when mc.IsActive=1 then mc.ClaimSubmissionID else 0 end) AS total_claim,
sum(case when mc.op=1 then mc.ClaimSubmissionID else 0 end) AS total_op
sum(case when mc.ip=1 then mc.ClaimSubmissionID else 0 end) AS total_ip
FROM dbo.MST_PriorAuthorization_Claim_Header mpach
INNER JOIN dbo.MS_Provider mp ON mp.Provider_ID = mpach.Provider_ID
JOIN dbo.MST_Claim mc ON mc.HeaderID = mpach.HeaderID;

Selecting columns based on a case SQL

I'm wondering how I can return specific results depending on my first selected statement. Basically I have two IDs. CustBillToID and CustShipToID. If CustShipToID is not null I want to select that and all the records that are joined to it. If it is null default to the CustBillToID and all the results that are joined to that.
Here is my SQL that obviously doesn't work. I should mention I tried to do a sub query in the conditional, but since it returns multiple results it won't work. I am using SQL Server 2012.
SELECT CASE WHEN cp.CustShipToID IS NOT NULL
THEN
cy.CustDesc,
cy.Address1,
cy.Address2,
cy.City,
cy.State,
cy.ZIP,
cy.Phone
ELSE
c.CustDesc,
c.Address1,
c.Address2,
c.City,
c.State,
c.ZIP,
c.Phone
END
LoadID,
cp.CustPOID,
cp.POBillToRef,
cp.POShipToRef,
cp.CustBillToID,
cp.CustShipToID,
cp.ArrivalDate,
cp.LoadDate,
cp.StopNum,
cp.ConfNum,
cp.EVNum,
cp.ApptNum,
ld.CarrId,
ld.Temperature,
cr.CarrDesc
FROM [Sales].[dbo].[CustPO] AS cp
LEFT OUTER JOIN Load AS ld
ON cp.LoadID = ld.LoadID
LEFT OUTER JOIN Carrier AS cr
ON ld.CarrId = cr.CarrId
LEFT OUTER JOIN Customer AS c
ON c.CustId = cp.CustBillToID
WHERE CustPOID=5213
Any ideas?
Also my current SQL is below, I do a conditional to determine if it's set. I'd rather do it in SQL if possible.
SELECT cp.LoadID,
cp.CustPOID,
cp.POBillToRef,
cp.POShipToRef,
cp.CustBillToID,
cp.CustShipToID,
cp.ArrivalDate,
cp.LoadDate,
cp.StopNum,
cp.ConfNum,
cp.EVNum,
cp.ApptNum,
ld.CarrId,
ld.Temperature,
cr.CarrDesc,
c.CustDesc as CustBillToDesc,
c.Address1 as CustBillAddress1,
c.Address2 as CustBillAddress2,
c.City as CustBillCity,
c.State as CustBillState,
c.ZIP as CustBillZIP,
c.Phone as CustBillPhone,
cy.CustDesc as CustShipToDesc,
cy.Address1 as CustShipAddress1,
cy.Address2 as CustShipAddress2,
cy.City as CustShipCity,
cy.State as CustShipState,
cy.ZIP as CustShipZIP,
cy.Phone as CustShipPhone
FROM [Sales].[dbo].[CustPO] as cp
left outer join Load as ld
on cp.LoadID = ld.LoadID
left outer join Carrier as cr
on ld.CarrId = cr.CarrId
left outer join Customer as c
on c.CustId = cp.CustBillToID
left outer join Customer as cy
on cy.CustId = cp.CustShipToID
WHERE CustPOID=?
You need a separate case for each column:
SELECT (CASE WHEN cp.CustShipToID IS NOT NULL THEN cy.CustDesc ELSE c.CustDesc END) as CustDesc,
(CASE WHEN cp.CustShipToID IS NOT NULL THEN cy.Address1 ELSE c.Address1 END) as Address1,
(CASE WHEN cp.CustShipToID IS NOT NULL THEN cy.Address2 ELSE c.Address2 END) as Address2,
(CASE WHEN cp.CustShipToID IS NOT NULL THEN cy.City ELSE c.City END) as City,
(CASE WHEN cp.CustShipToID IS NOT NULL THEN cy.State ELSE c.State END) as State,
(CASE WHEN cp.CustShipToID IS NOT NULL THEN cy.ZIP ELSE c.ZIP END) as ZIP,
(CASE WHEN cp.CustShipToID IS NOT NULL THEN cy.Phone ELSE c.Phone END) as Phone,
. . .
For this, you basically want to build a string that is your SQL and then execute the string...look # the answer to this one ::
SQL conditional SELECT
Did you try coalesce(CustShipToID,CustBillToID ) ?
...
FROM [Sales].[dbo].[CustPO] as cp
left outer join Load as ld
on cp.LoadID = ld.LoadID
left outer join Carrier as cr
on ld.CarrId = cr.CarrId
inner join Customer as c
on c.CustId = coalesce(cp.CustShipToID,cp.CustBillToID )
...