SQL选择具有特定值的不同ID

时间:2020-10-16 08:36:29

标签: sql group-by subquery distinct having-clause

您能否告诉我如何查找具有FormFieldID((1和2)或3)的用户,所以SQL查询应返回UserID:7、8、9。

表格:

The table

我使用SQL Server。

谢谢!

1 个答案:

答案 0 :(得分:0)

我建议使用聚合和having子句来实现过滤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

取决于您未告知的实际数据库,可能会有更整洁的选项来表达条件。例如,在MySQL中:

having 
    (max(formfieldid = 1) and max(formfieldid = 2))
    or max(formfieldid = 3)
相关问题