Sql select 基于其他行中的值
Sql select based on the value in other rows
我有一个 table 如下所示:
DS_no Value Language Nach
1 0 EN 123
2 ABC EN 123
2 DCEF EN 123
1 1 EN 122
2 XZU EN 122
2 SDF EN 122
所以我希望我的 select 语句检查 DS_no 的值是否每个 nach 都为 1。如果该值为 1,那么它应该 select 该 nach 的所有其他值。例如。 nach 122 的 ds_no 1。如果 ds_no 1 的值为 0,则 select 不应 return 任何值。
例如:nach 123 的 ds_no 1 的值为 0。所以我不想 select nach 123 的任何值。但是 nach 122 的 ds_no 1 有值 1。所以我想 select nach 122 的所有值,除了值 1。
没有第一个值。但是您可以使用 exists
:
检查 any 值是否为 0
select t.*
from t
where exists (select 1
from t t2
where t2.nach = t.nach and t2.value = '0'
);
您发布的示例数据
SQL> select * from test;
DS_NO VALU NACH
---------- ---- ----------
1 0 123
2 abc 123
2 dcef 123
1 1 122
2 xzu 122
2 sdf 122
6 rows selected.
查询 returns 您所描述的内容,并附注您 - 很可能 - 在此处输入错误:
so i want to select all the values of nach 123 except the value 1.
123
应该是 122
,我想。
SQL> select ds_no, value, nach
2 from test a
3 where value <> '1'
4 and exists (select null
5 from test b
6 where b.nach = a.nach
7 and b.value = '1'
8 );
DS_NO VALU NACH
---------- ---- ----------
2 sdf 122
2 xzu 122
SQL>
我有一个 table 如下所示:
DS_no Value Language Nach
1 0 EN 123
2 ABC EN 123
2 DCEF EN 123
1 1 EN 122
2 XZU EN 122
2 SDF EN 122
所以我希望我的 select 语句检查 DS_no 的值是否每个 nach 都为 1。如果该值为 1,那么它应该 select 该 nach 的所有其他值。例如。 nach 122 的 ds_no 1。如果 ds_no 1 的值为 0,则 select 不应 return 任何值。
例如:nach 123 的 ds_no 1 的值为 0。所以我不想 select nach 123 的任何值。但是 nach 122 的 ds_no 1 有值 1。所以我想 select nach 122 的所有值,除了值 1。
没有第一个值。但是您可以使用 exists
:
0
select t.*
from t
where exists (select 1
from t t2
where t2.nach = t.nach and t2.value = '0'
);
您发布的示例数据
SQL> select * from test;
DS_NO VALU NACH
---------- ---- ----------
1 0 123
2 abc 123
2 dcef 123
1 1 122
2 xzu 122
2 sdf 122
6 rows selected.
查询 returns 您所描述的内容,并附注您 - 很可能 - 在此处输入错误:
so i want to select all the values of nach 123 except the value 1.
123
应该是 122
,我想。
SQL> select ds_no, value, nach
2 from test a
3 where value <> '1'
4 and exists (select null
5 from test b
6 where b.nach = a.nach
7 and b.value = '1'
8 );
DS_NO VALU NACH
---------- ---- ----------
2 sdf 122
2 xzu 122
SQL>