5

我正在尝试编写一个 where 子句,该子句将找到满足三个条件中至少两个的人。这是一个例子

   SELECT *
   FROM Personal
   WHERE
   [State] = 'Tx' or [City] = 'Austin' or [Gender] = 'Male'

所以它应该返回住在德克萨斯州和奥斯汀的任何人或住在德克萨斯州并且是男性的人等等,但不是只住在德克萨斯州的人,他们必须满足至少两个标准

我的真实查询可以有更多的条件,还包括大于两个或正好两个等等。

提前致谢

4

2 回答 2

6

您可以在一系列 case ... then 1 else 0 end 语句中添加匹配项,并将最终结果与所需匹配项的数量进行比较:

   SELECT *
   FROM Personal
   WHERE
     case when [State] = 'Tx' then 1 else 0 end
     + case when [City] = 'Austin' then 1 else 0 end
     + case when [Gender] = 'Male' then 1 else 0 end
     >= 2

或者,您可以将其分解为 union all 列表:

SELECT *
FROM   personal
       INNER JOIN (SELECT id
                   FROM   (SELECT id
                           FROM   personal
                           WHERE  state = 'Tx'
                           UNION ALL
                           SELECT id
                           FROM   personal
                           WHERE  city = 'Austin'
                           UNION ALL
                           SELECT id
                           FROM   personal
                           WHERE  gender = 'Male') a
                   GROUP  BY id
                   HAVING COUNT (*) >= 2) a
         ON personal.id = a.id 
于 2012-04-09T21:10:27.990 回答
2
 SELECT *
   FROM Personal
   WHERE
   ([State] = 'Tx' AND [City] = 'Austin') or ([State] = 'Tx' AND [Gender] = 'Male')
于 2012-04-09T21:08:09.390 回答