SQL select 具有一个特定值但在同一 table 中没有另一个的行
SQL select rows that have one specific value but not another in the same table
我有一个 table 这样的:
DOC
DATE
KEY
HOUR
DEPARTAMENT
STATUS
99KN001000002
2000-12-28
12:04:51
DEP 1
99KN001000002
2000-12-28
12:05:35
DEP 2
99KN001000002
2000-12-28
12:06:31
DEP 3
99KN001000002
2000-12-28
12:07:17
DEP 4
99KN001000003
2000-12-29
12:07:17
DEP 1
我想找出所有以“DEP 1”作为唯一记录的文档
这应该适用于任何 RDBMS:
select DOC from table_name
where DEPARTAMENT = 'DEP 1'
and DOC not in
(select DOC from table_name where DEPARTAMENT <> 'DEP 1');
如果您的 RDBMS 支持,您可以使用 MINUS
或 EXCEPT
。
另一种方式:
select t.*
from test_tbl t
inner join (select doc,
count(distinct STATUS) as nr_status
from test_tbl
group by doc
) as t1 on t.doc=t1.doc
where t1.nr_status =1 ;
我有一个 table 这样的:
DOC | DATE | KEY | HOUR | DEPARTAMENT | STATUS |
---|---|---|---|---|---|
99KN001000002 | 2000-12-28 | 12:04:51 | DEP 1 | ||
99KN001000002 | 2000-12-28 | 12:05:35 | DEP 2 | ||
99KN001000002 | 2000-12-28 | 12:06:31 | DEP 3 | ||
99KN001000002 | 2000-12-28 | 12:07:17 | DEP 4 | ||
99KN001000003 | 2000-12-29 | 12:07:17 | DEP 1 |
我想找出所有以“DEP 1”作为唯一记录的文档
这应该适用于任何 RDBMS:
select DOC from table_name
where DEPARTAMENT = 'DEP 1'
and DOC not in
(select DOC from table_name where DEPARTAMENT <> 'DEP 1');
如果您的 RDBMS 支持,您可以使用 MINUS
或 EXCEPT
。
另一种方式:
select t.*
from test_tbl t
inner join (select doc,
count(distinct STATUS) as nr_status
from test_tbl
group by doc
) as t1 on t.doc=t1.doc
where t1.nr_status =1 ;