I have two queries that find both the Zip codes, and the States for all the respondents in our database. Here they are
For ZIP code:
select top 100 S.ID as SurveyID, S.SID, S.SurveyNumber, S.ABCSurveyName, SE.RespondentID, Q.name as QuestionName, rp.Condition as ZipCode
from Surveys S
join Sessions SE
on S.id = SE.SurveyID
join RespondentProfiles rp
on RP.RespondentID = SE.RespondentID
join Questions Q
on Q.ID = rp.QuestionID
where q.name = 'ZIP'
and S.ID = 13900
and Q.LK_RecordStatusID = 1
For state:
select VW.ID as SurveyID, VW.SID, SurveyNumber, ABCSurveyName, RespondentID, VW.Name as QuestionName, st.Code as State
from (
select top 100 S.ID, S.SID, S.SurveyNumber, S.ABCSurveyName, SE.RespondentID, Q.name, rp.Condition
from Surveys S
join Sessions SE
on S.id = SE.SurveyID
join RespondentProfiles rp
on RP.RespondentID = SE.RespondentID
join Questions Q
on Q.ID = rp.QuestionID
where S.ID = 13900
and q.name = 'STATE'
and Q.LK_RecordStatusID = 1
) VW
join LK_States st
on st.ID = vw.Condition
This works, but I’d like to have them all in one table, i.e. Zip Code and State.
Thanks!
questions schema:
Column_name Type Computed Length Prec Scale Nullable
TrimTrailingBlanks FixedLenNullInSource Collation
ID int no 4 10 0 no (n/a) (n/a) NULL
SID nvarchar no 128 yes (n/a) (n/a) SQL_Latin1_General_CP1_CI_AS
Name nvarchar no 64 yes (n/a) (n/a) SQL_Latin1_General_CP1_CI_AS
QuestionIdentifier nvarchar no 128 yes (n/a) (n/a) SQL_Latin1_General_CP1_CI_AS
ParentID int no 4 10 0 yes (n/a) (n/a) NULL
LK_QuestionTypeID int no 4 10 0 yes (n/a) (n/a) NULL
LK_QuestionCategoryID int no 4 10 0 yes (n/a) (n/a) NULL
LK_IndustryID int no 4 10 0 yes (n/a) (n/a) NULL
OptionMask nvarchar no 512 yes (n/a) (n/a) SQL_Latin1_General_CP1_CI_AS
MetaTags ntext no 16 yes (n/a) (n/a) SQL_Latin1_General_CP1_CI_AS
Order int no 4 10 0 yes (n/a) (n/a) NULL
Rows int no 4 10 0 yes (n/a) (n/a) NULL
Columns int no 4 10 0 yes (n/a) (n/a) NULL
IsDisplay bit no 1 yes (n/a) (n/a) NULL
AnswerLifespan int no 4 10 0 yes (n/a) (n/a) NULL
CreateUserID int no 4 10 0 yes (n/a) (n/a) NULL
CreateDate datetime no 8 yes (n/a) (n/a) NULL
UpdateUserID int no 4 10 0 yes (n/a) (n/a) NULL
UpdateDate datetime no 8 yes (n/a) (n/a) NULL
LK_RecordStatusID bit no 1 yes (n/a) (n/a) NULL
LK_QuestionClassID int no 4 10 0 yes (n/a) (n/a) NULL
LK_QuestionVisibilityID int no 4 10 0 yes (n/a) (n/a) NULL
DisplayLK_QuestionTypeID int no 4 10 0 yes (n/a) (n/a) NULL
Well, I did not take time to remove unnecessary selected fields but here is an ugly query that should get pretty close. Essentially your ‘State’ query was recasting most of the joins as a sub query anyway:
All I did was add an extra sub-query to join on at the top level. I think there may be a more efficient query but since it is a
SELECT TOP 100, I’m not sure performance will be an issue.Not checked for errors but here is the entire monster: