我对SQL还是很陌生,所以如果发现这个问题很傻,请原谅。
表格
+--------------------+
id state isPresent
+--------------------+
id1 1 N
id2 2 N
id2 2 Y
id3 3 N
id4 4 N
id4 4 Y
id5 2 N
id5 2 Y
对于特定状态,我需要获取所有isids = N和isPresent = Y的单调ID。
例如, 如果将2(状态)作为参数传递给查询,由于该状态的isPresent =“ N”和“ Y”,我们应该得到的结果分别为id2和id5。
Similary,如果我们通过4,我们应该只获得id4
使用Sybase
答案 0 :(得分:0)
尝试使用内部联接,如下所示:
SELECT DISTINCT(id)
FROM table t1 INNER JOIN table t2
ON t1.id = t2.id
AND t1.isPresent != t2.isPresent
WHERE state = 2
我们正在使用ID字段相同且isPresent
字段将Y保持为Y而将另一个保持为N的形式对表进行内部联接。我将状态硬编码为2,但是您可以对其进行参数化并使用它以编程方式在准备好的语句中动态传递它。
答案 1 :(得分:0)
看起来像带有WHERE
的简单DISTINCT
子句可以完成您的解释。
您需要第11-14行。
SQL> with test (id, state, ispresent) as
2 (select 'id1', 1, 'N' from dual union all
3 select 'id2', 2, 'N' from dual union all
4 select 'id2', 2, 'Y' from dual union all
5 select 'id3', 3, 'N' from dual union all
6 select 'id4', 4, 'N' from dual union all
7 select 'id4', 4, 'Y' from dual union all
8 select 'id5', 2, 'N' from dual union all
9 select 'id5', 2, 'Y' from dual
10 )
11 select distinct id
12 from test
13 where ispresent = 'N'
14 and state = &par_id;
Enter value for par_id: 2
ID
---
id2
id5
SQL> /
Enter value for par_id: 4
ID
---
id4
SQL>
答案 2 :(得分:0)
我想您想返回一个单独的id
,只要N
列同时具有两种情况(Y
和isPresent
)即可。因此,考虑通过更改参数(现在为exists
)将以下SQL语句与2
运算符一起使用:
with tab(id, state, isPresent) as
(
select 'id1', 1, 'N' union all
select 'id2', 2, 'N' union all
select 'id2', 2, 'Y' union all
select 'id3', 3, 'N' union all
select 'id4', 4, 'N' union all
select 'id4', 4, 'Y' union all
select 'id5', 2, 'N' union all
select 'id5', 2, 'Y'
)
select distinct id
from tab t1
where exists ( select 1
from tab t2
where t2.state = t1.state
and t2.isPresent in ('N','Y') -- this line might be commented out, if it's certain that there're only two cases "N" and "Y"
group by t2.state
having count(distinct t2.isPresent) = 2
)
and t1.state = 2 -- try other values also such as 1, 3, 4
对于值1
和3
,将不返回任何行,而对于2
和4
,则至少返回一行。