【问题标题】:SQL selecting distinct Ids with specific valuesSQL 选择具有特定值的不同 ID
【发布时间】:2021-01-30 18:29:05
【问题描述】:

您能否告诉我如何使用 FormFieldID ((1 AND 2) OR 3) 查找用户,因此 SQL 查询应返回 UserID:7、8、9。

桌子:

我使用 SQL Server。

谢谢!

【问题讨论】:

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


    【解决方案1】:

    我会推荐聚合和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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 2019-07-06
      • 2011-12-28
      • 1970-01-01
      相关资源
      最近更新 更多