表t
为
|id| sport |
|1 | football |
|1 | football |
|1 | baseball |
|2 | football |
|2 | football |
|3 | football |
|4 | football |
|4 | golf |
|4 | golf |
|4 | baseball |
|4 | football |
|5 | football |
|5 | football |
|6 | basketball |
|6 | football |
|6 | football |
按id
分组,我如何仅选择所有运动值=足球的ID?像这样
SELECT * FROM t
GROUP BY id
HAVING ALL SPORT = 'football'
为了返回
|id| sport |
|2 | football |
|2 | football |
|3 | football |
|5 | football |
|5 | football |
答案 0 :(得分:2)
您可以使用条件聚合:
SELECT *
FROM tab
WHERE id IN (SELECT id
FROM t
GROUP BY id
HAVING SUM(CASE WHEN sport != 'football' THEN 1 ELSE 0 END) = 0);
我需要进行哪些调整才能将...体育=足球的所有值转换为体育=足球的任何值?
SELECT *
FROM tab
WHERE id IN (SELECT id
FROM t
WHERE sport = 'football');
答案 1 :(得分:2)
这是简单的解决方案:
SELECT *
FROM t
WHERE id IN (
SELECT id
FROM t
GROUP BY id
HAVING COUNT(CASE WHEN sport = 'football' THEN 1 END) = COUNT(*)
)
答案 2 :(得分:1)
在所有值都相同的列中,最小值和最大值相等。您可以在having
子句中使用此属性:
SELECT id, MAX(sport)
FROM t
GROUP BY id
HAVING MIN(sport) = 'football' AND MAX(sport) = 'football'
答案 3 :(得分:1)
如果要原始行,请使用not exists
:
select t.*
from t
where t.sport = 'footbal' and
not exists (select 1
from t2
where t2.id = t.id and t2.sport <> t.sport
);
否则,请使用
having min(sport) = max(sport) and max(sport) = 'football'
答案 4 :(得分:1)
根据上述问题中的描述,作为解决方案,请尝试执行以下SQL select查询
select * from(SELECT id, sport FROM `t`
group by id, sport) as q group by q.id having count(q.id) = 1
and sport = 'football'