I need to select certain records with cases from multiple tables and I need to select them based on some cases that I will create.
This is what I have so far for my query:
select distinct top 10
QuestionTag =( CASE
WHEN qt.id = 98 THEN 'Save the Sale TP'
WHEN qt.id = 99 THEN 'Close the Loop'
WHEN qt.id != 98 AND qt.id != 99 THEN ''
WHEN qt.id = 98 AND qt.id = 99 THEN 'Save the Sale TP'
END),
c.contactid as contactid, c.first, c.last,
st.datecomplete, st.ownerIdfk, st.finalScore, st.surveyid,
cc.clientcontactid, cc.leadsource,
se.eventdate, se.ProcedureName, se.LocationName, se.salesperson, se.SpecialistName, st.surveyname
from sigweb.dbo.survey_tracking st
join sigweb.dbo.survey_types_main stm on st.surveyid = stm.surveyidfk
join sigweb.dbo.contact c on st.contactid = c.contactid
join survey.dbo.client_contacts cc on c.contactid = cc.contactidfk
join survey.dbo.survey_events se on c.contactid = se.contactidfk
join survey.dbo.results r on r.owneridfk = st.owneridfk
left join survey.dbo.questionsAdmin qa on qa.questionidfk = r.questionidfk
join survey.dbo.QuestionTags qt on qt.id=qa.tagidfk
This is part of the output:
QuestionTag ContactID First Last
----------- --------- ----- ----
2012082911569010000001 John Reardon
Close the Loop 2012082911569010000001 John Reardon
Save the Sale TP 2012082911569010000001 John Reardon
2012082911569010000003 Beverly Conley
Close the Loop 2012082911569010000003 Beverly Conley
Save the Sale TP 2012082911569010000003 Beverly Conley
2012082911569010000009 Larry Grigsby
2012082911569010000011 Brenda Bain
2012082911569010000012 Richard Pecora
2012082911569010000018 Karl Oliszczak
I need to add a “where” to select only one of the duplicate records based on these cases:
IF a contactid has only CTL then select that
IF a contactid has only STS TP then select that
IF a contact appears more than once and it has ” and CTL and STS TP then output only the STS TP
IF a contact does not have CL or STS TP then do not output the contact at all.
I was thinking that I need to add one more case inside my WHERE clause but I was wondering if there is another method that will save me time and code writing
This is my improved attempt. It does what it is supposed to do but it is kind of slow.