tags:

views:

84

answers:

2

I have the following query to retrieve customers who answer YES to a particular question "OR" NO to another question.

SELECT customers.id
FROM customers, responses
WHERE (
(
responses.question_id = 5
AND responses.value_enum = 'YES'
)
OR (
responses.question_id = 9
AND responses.value_enum = 'NO'
)
)
GROUP BY customers.id

Which works fine. However I wish to change the query to retrieve customers who answer YES to a particular question "AND" answer NO to another question.

Any ideas on how I can achieve this?

PS - The responses above table is in an EAV format ie. a row represents an attribute rather than a column.

A: 

Approximately as such:

SELECT distinct
  c.id
FROM 
  customers c
WHERE
  exists (select 1 from responses r where r.customer_id = c.id and r.response_id = 5 and r.value_enum = 'YES')
  and exists (select 1 from responses r2 where r2.customer_id = c.id and r2.response_id = 9 and r2.value_enum = 'NO')

I made an assumption on the missing join condition, modify as correct for your schema.

Donnie
Donnie thanks very much for that it does exactly what I need! Can anybody recommend any books/resources for someone looking to learn more advanced sql stuff like this?
Ian
+2  A: 

I'm assuming that you have a column called customer_id in your responses table. Try joining the responses table to itself:

SELECT Q5.customer_id
FROM responses Q5
JOIN responses Q9 ON Q5.customer_id = Q9.customer_id AND Q9.question_id = 9
WHERE Q5.question_id = 5
AND Q5.value_enum = 'YES'
AND Q9.value_enum = 'NO'
Mark Byers
+1 this is a lot more simple than how I was thinking to do it. Nice.
northpole
Yep that returns the same result for me as Donnie's query. The help here is great can't thank you enough.
Ian