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.
I have the following tablesAqID Question1 What day is it?2 How many are there?3 Do you have green?BqID CategoryID1 11 32 13 2The problem I have is that I am trying to apply filters to the questions to return them to the user. It is fine if i want to just return say all of the Questions that are in CategoryID = 1.I can just do SELECT A.QuestionID, A.Question, B.CategoryID FROM A INNER JOIN B ON A.qID = B.qIDWHERE CategoryID = 1This will returnqID Question CategoryID1 What day is it? 12 How many are there? 1I can even return which questions are in either CategoryID = 1 OR CategoryID = 3.qID Question CategoryID1 What day is it? 11 What day is it? 32 How many are there? 1then use the DESTINCT to only return qID= 1 once.The problem I have is that when I apply two Category Filters, CategoryID = 1 and CategoryID = 3 then I will not work. I am completely aware of why this is, but is there not a way where I can look through the table and return the question only when it appears twice, once with CategoryID = 1 and once with CategoryID = 3?I hope I made this pretty clear. Thanks in advance for any help.
Ifor
Aged Yak Warrior
700 Posts
Posted - 2007-07-03 : 13:19:37
Maybe something like:
SELECT *FROM AWHERE EXISTS ( SELECT * FROM B B1 WHERE A.qID = B1.qID AND B1.CategoryID = 1 ) AND EXISTS ( SELECT * FROM B B2 WHERE A.qID = B2.qID AND B2.CategoryID = 3 )
or
SELECT A.*FROM A JOIN ( SELECT B.qID FROM B WHERE B.CategoryID IN (1,3) GROUP BY B.qID HAVING COUNT(*) = 2 ) D ON A.qID = D.qID
etc
tentonipete
Starting Member
4 Posts
Posted - 2007-07-31 : 13:28:04
Thanks for your help, in the end I went with a variation on the second of your suggestions as that seemed simpler given my data.