Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi all,I'm having a problem working the SQL out for the following:I have a table Person:personId----------name1----------------Robert2----------------Frank and another table QuestionpersonId------questionId---------answer1-------------1-----------------Y1-------------2-----------------Y1-------------3-----------------Y2-------------1-----------------Y2-------------2-----------------Y2-------------3-----------------Nand I am trying to find a way of returning a list of ids of people who have answered Y to the first and second questions but N to the third.If I try:SELECT DISTINCT personId FROM Person INNER JOIN Question ON question.personId = Person.personIdWHERE (Question.questionId = '1') AND (Question.answer = 'Y') AND (Question.questionId = '2') AND (Question.answer = 'Y') AND (Question.questionId = '3') AND (Question.answer = 'N')I get no records returned. Anyone's help here would be much appreciated as this is driving me mad.
rrb
SQLTeam Poet Laureate
1479 Posts
Posted - 2005-04-20 : 23:26:11
at first glance I think you need to join the table three timesselect personId from person p, question q1, question q2, question q3 where (person.id = q1.personid and q1.questionid = 1 and q1.answer = 'Y')and (person.id = q2.personid and q2.questionid = 2 and q2.answer = 'Y')and (person.id = q3.personid and q3.questionid = 3 and q3.answer = 'N')try that and let me know how you go (sorry can't test it)--I hope that when I die someone will say of me "That guy sure owed me a lot of money"
Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)
7020 Posts
Posted - 2005-04-21 : 02:19:40
This should do it:
SELECT a.personIdFROM Person a INNER JOIN Question b ON b.personId = a.personIdwhere b.questionId in (1,2,3)group by a.personIdhaving sum( case when b.questionId in (1,2) and b.answer = 'Y' then 1 when b.questionId in (3) and b.answer = 'N' then 1 else 0 end) = 3