我正在尝试编写一个where子句,该子句将找到满足三个条件中至少两个的人。 这是一个例子
SELECT *
FROM Personal
WHERE
[State] = 'Tx' or [City] = 'Austin' or [Gender] = 'Male'
所以它应该归还任何住在德克萨斯州和奥斯汀或生活在德克萨斯州并且是男性等等的人,但不是那些只住在德克萨斯州的人,他们必须满足至少两个标准
我的真实查询可以有更多标准,还包括大于两个或恰好两个等等。
提前致谢
答案 0 :(得分:4)
您可以在一系列案例中添加匹配...然后另外还有0个结束语句,并将最终结果与所需匹配项的数量进行比较:
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
答案 1 :(得分:1)
SELECT *
FROM Personal
WHERE
([State] = 'Tx' AND [City] = 'Austin') or ([State] = 'Tx' AND [Gender] = 'Male')