Search code examples
sqlgroup-bysubquerydistincthaving-clause

SQL selecting distinct Ids with specific values


Could you tell me please how to find users with FormFieldID ((1 AND 2) OR 3), so the SQL query should return UserIDs: 7, 8, 9.

The table:

The table

I use SQL Server.

Thank you!


Solution

  • I would recommend aggregation and having clause to implement the filtering logc:

    select userid
    from mytable
    group by userid
    having 
        (
             max(case when formfieldid = 1 then 1 end) = 1 
             and max(case when formfieldid = 2 then 1 end) = 1
        )
        or max(case when formfieldid = 3 then 1 end) = 1
    

    Depending on your actual database, which you did not tell, there may be neater options to express the conditions. For example, in MySQL:

    having 
        (max(formfieldid = 1) and max(formfieldid = 2))
        or max(formfieldid = 3)