3

I have a table Data which contains some data. Several rows belong to the same customer having the same customer_id (index to Customers table). This customer has answered some questions which they have question_id (index to Questions table). In the Data table, there is also the value column regarding the answer of the customer to question0

Data Table

I am trying to select the customer_id for which the answers to question_id 1, 2, 3 are 0

I have also tried

SELECT distinct customer_id
FROM Data
WHERE value = 0
AND question_id IN (1, 2, 3);

but I am not getting the appropriate result which should be 24 which is the customer_id of the customer that has answered 0 to the questions with question_id 1, 2 and 3.

2
  • 4
    Specify the expected result as well. (Having the above table data.) BTW, most people here want formatted text, not images. Commented Jan 17, 2018 at 13:22
  • Both answers given by the Wanderer and Gordon Linoff are correct. Commented Jan 30, 2018 at 9:18

2 Answers 2

2

You are close. You can get what you want using group by and having:

SELECT customer_id
FROM Data
WHERE value = 0 AND question_id IN (1, 2, 3)
GROUP BY customer_id
HAVING COUNT(DISTINCT question_id) = 3;

The HAVING clause specifies that all three questions are answered -- and that the answers are 0.

Sign up to request clarification or add additional context in comments.

Comments

1

An alternative way with GROUP BY and HAVING.

Query

select `customer_id`
from `your_table_name`
where `question_id` in (1,2,3)
group by `customer_id`
having sum(`value`) = 0;

Find a demo here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.