我想从'num'中选择不同的值,因为它的状态仅为'YES',一次不包括'NO'?
表:
+--------+-----+--------+
| id | num | status |
+--------+-----+--------+
| 364519 | AAA | YES |
| 364522 | BBB | YES |
| 364525 | AAA | NO |
| 364527 | CCC | YES |
| 364530 | DDD | YES |
| 364532 | EEE | YES |
| 364535 | FFF | YES |
| 364537 | DDD | YES |
| 364538 | DDD | NO |
| 364539 | FFF | NO |
+--------+-----+--------+
需要结果:
+--------+-----+--------+
| id | num | status |
+--------+-----+--------+
| 364522 | BBB | YES |
| 364527 | CCC | YES |
| 364532 | EEE | YES |
+--------+-----+--------+
答案 0 :(得分:2)
您可以使用HAVING
:
SELECT MIN(id) AS id, num,'yes' AS status
FROM tab
GROUP BY num
HAVING SUM(status='NO') = 0;
<强> DBFiddle Demo 强>
答案 1 :(得分:1)
其他几种方法。 (看起来最干净)
将数据分成两组,并确保&#34; A&#34; set在&#34; B&#34;中没有数据。组 使用外连接的第一种方法仅返回&#34; A&#34;设置在&#34; B&#34;中找不到相关数量的地方集。
SELECT Min(A.ID) as ID, A.num, A.status
FROM table A
LEFT JOIN table B
on A.Num = B.Num
and B.Status = 'NO'
WHERE A.Status = 'YES'
and B.Num is null
GROUP BY A.Num, A.Status
使用不存在的第二种方法。在&#34; A&#34;中只有类似的num记录不在&#34; B&#34;集。
SELECT min(A.ID) as ID, A.Num, A.Status
FROM table A
WHERE NOT EXISTS (SELECT 1
FROM Table B
WHERE A.Num = B.Num
and B.Status = 'NO')
GROUP BY A.Num, A.Status
答案 2 :(得分:0)
SELECT * FROM table
WHERE status='YES' AND num NOT IN (SELECT num FROM table WHERE status='NO')
或者这个
SELECT * FROM table t
WHERE t.status='YES' AND NOT EXISTS (SELECT * FROM table WHERE status='NO' AND num=t.num)
答案 3 :(得分:0)
从表中选择不同(num),id,状态=&#39;是&#39;
答案 4 :(得分:0)
我只会使用group by
cluase:
select min(id) as id, num, 'YES' as status
from table t
group by num
having min(status) = max(status) and min(status) = 'YES';