Q:

Fetch row with different data on same column

We have the table structure like 
Fieldid userid data
41       2      1
12       2      0
41       3      1
12       3      1

We want the user which have (data=1 and filedid = 41) and (data = 0 and filedid=12)
We tried the query 
select userid from table 
where (data=1 and filedid = 41) 
AND (data = 0 and filedid=12)

but it returns empty results. 
Can anyone help how we will get the record using MySQL?

A:

You can use grouping with a conditional aggregate in the HAVING clause:
SELECT userid
FROM mytable
GROUP BY userid
HAVING COUNT(CASE WHEN data = 1 AND FieldId = 1 THEN 1 END) >= 1 AND
       COUNT(CASE WHEN data = 0 AND FieldId = 12 THEN 1 END) >= 1

