在distinct条件下选择distinct列

ars1skjm  于 2021-06-20  发布在  Mysql
关注(0)|答案(5)|浏览(330)

当“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    |
+--------+-----+--------+
sy5wg1nm

sy5wg1nm1#

从status='yes'的表中选择distinct(num)、id、status

zvms9eto

zvms9eto2#

我只想用 group by 俱乐部:

select min(id) as id, num, 'YES' as status
from table t
group by num
having min(status) = max(status) and min(status) = 'YES';
uplii1fm

uplii1fm3#

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)
dluptydi

dluptydi4#

只是一些其他的方法((看起来是最干净的)
将数据分为两组,并确保“a”组在“b”组第一种方法中没有数据,在“a”组中使用仅限外部连接的返回记录,在“b”组中找不到相关的num。

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

第二种方法不存在。类似的只有“a”集中的num记录,而不是“b”集中的num记录。

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
ewm0tg9j

ewm0tg9j5#

你可以用 HAVING :

SELECT MIN(id) AS id, num,'yes' AS status
FROM tab
GROUP BY num
HAVING SUM(status='NO') = 0;

dbfiddle演示

相关问题