简体   繁体   中英

How Do I Exclude Data Based on Column Values in SQL?

I have a table which is set up like this:

Name        QuestionCd  Response
John Smith  837987      3
John Smith  837988      NULL
John Smith  837991      3
John Smith  837996      3
John Smith  838003      NULL
Mary Smith  837987      1
Mary Smith  837988      1
Mary Smith  837991      3
Mary Smith  837996      1
Mary Smith  838003      5

I need to bring in the customer who has a response for all 5 questions, which would be Mary Smith. I've tried to use a case statement to flag the rows that have a response but that would be incorrect since John Smith did not answer all of the questions.

I've tried the following:

-- Case when QuestionCd between '837987' and '838069' and response is null then '' else 'X' end

-- Case when QuestionCd between '837987' and '838069' and Response is null then '' when QuestionCd between '837987' and '838069' and Response is not null then 'x' end

Any ideas or tips on how to accomplish this? Thank you kindly for your help.

This is how I would do it.

SELECT Name
FROM 
(
  SELECT Name, QuestionCd
  FROM <YourTable>
  WHERE NOT Response IS NULL
  GROUP BY Name, QuestionCd
) SQ
GROUP BY Name
HAVING COUNT(QuestionCd)=5

The sub query is to have a distinct list of question answered since Mary Smith or John Smith may have answered the question more than one.

If the question ID's are fixed you can just return the name of the person who has answered 5 unique questions

 SELECT Name FROM tbl 
 GROUP BY Name
 HAVING count(QuestionCD) = 5 

Edit - fixed SQL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM