我的表格有两列,如下所示:
ROLE_ID RESTRICTION_ID
--------- ---------------
2 null
2 15
2 null
13 12
13 null
13 13
555 null
555 null
555 null
91 10
91 12
91 null
我需要得到:
ROLE_ID RESTRICTION_ID
--------- ---------------
555 null
555 null
555 null
意思是,我需要所有没有连接到任何RESTRICTION_ID的ROLE_ID。
如果某个ROLE_ID的RESTRICTION_ID列中有一些数字,则希望从select语句结果中排除ROLE_ID。
答案 0 :(得分:2)
选择resctriction_id为空的行
select * from my_table
where resctiction_id is null
and role_id not in (select role_id from my_table where resctiction_id is not null) ;
答案 1 :(得分:2)
SELECT t1.*
FROM
table t1
LEFT JOIN table t2
ON t1.ROLE_ID = t2.ROLE_ID
AND t2.RESTRICTION_ID IS NOT NULL
WHERE
t2.ROLE_ID IS NULL
仅仅因为其他人都在显示WHERE IN(选择...这里的答案是一种通过自我加入来实现的方式......
只是为了表明使用EXISTS可以完成的一种方式......
SELECT t1.*
FROM
table t1
WHERE
NOT EXISTS (SELECT *
FROM
table t2
WHERE
t1.ROLE_ID = t2.ROLE_ID
AND t2.RESTRICTION_ID IS NOT NULL)
答案 2 :(得分:0)
SELECT ROLE_ID, RESTRICTION_ID
FROM Table
WHERE
ROLE_ID NOT IN (SELECT ROLE_ID FROM Table WHERE RESTRICTION_ID IS NOT NULL)
答案 3 :(得分:0)
SELECT ROLE_ID, RESTRICTION_ID
FROM <Your Table>
WHERE RESTRICTION_ID IS NULL
AND ROLE_ID NOT IN
(SELECT ROLE_ID FROM <Your Table> WHERE RESTRICTION_ID IS NOT NULL) sub
答案 4 :(得分:0)
Select role_id, restriction_id
From Table
Where role_id in (Select ROLE_ID
From Table
Group by ROLE_ID
Having COUNT(RESTRICTION_ID)=0)
更好的可能......
答案 5 :(得分:0)
以下内容可以帮助您入门:
SELECT
role_id
, restriction_id
FROM Data
WHERE role_id NOT IN
(SELECT
role_id
FROM Data
GROUP BY role_id
HAVING COUNT(restriction_id) > 0
);
请评论是否需要调整/进一步详细说明。
答案 6 :(得分:0)
并且因为你在这里标记了SQL是一个具有公共表表达式的Window函数,它也可以很好地完成工作。
WITH cte AS (
SELECT
*
,COUNT(RESTRICTION_ID) OVER (PARTITION BY ROLE_ID) as CountOfRestrictionsIds
FROM
TableName
)
SELECT *
FROM
cte
WHERE
CountOfRestrictionsIds = 0
答案 7 :(得分:0)
全部算上
with t as (
-- sample data
select 2 as ROLE_ID ,null as RESTRICTION_ID from dual union all
select 2 ,15 from dual union all
select 2 ,null from dual union all
select 13 ,12 from dual union all
select 13 ,null from dual union all
select 13 ,13 from dual union all
select 555 ,null from dual union all
select 555 ,null from dual union all
select 555 ,null from dual union all
select 91 ,10 from dual union all
select 91 ,12 from dual union all
select 91 ,null from dual
)
select ROLE_ID,RESTRICTION_ID
from (
select t.*
,count(RESTRICTION_ID) over(partition by ROLE_ID) as cnt
from t
) x
where cnt=0;