基本上我需要结合这两个查询的结果,其中 PSROLEUSER 在两个表中都相等。我该怎么做?
select PSROLEUSER from sysadm.PSROLEUSER where ROLENAME = 'NCC_Manag';
select PSROLEUSER from sysadm.PSROLEUSER where ROLENAME = 'HRM-Content Amin';
基本上我需要结合这两个查询的结果,其中 PSROLEUSER 在两个表中都相等。我该怎么做?
select PSROLEUSER from sysadm.PSROLEUSER where ROLENAME = 'NCC_Manag';
select PSROLEUSER from sysadm.PSROLEUSER where ROLENAME = 'HRM-Content Amin';
下面的查询假定ROLENAME
每个PSROLEUSER
.
SELECT PSROLEUSER
FROM sysadm.PSROLEUSER
WHERE ROLENAME IN ('NCC_Manag', 'HRM-Content Amin')
GROUP BY PSROLEUSER
HAVING COUNT(*) = 2
这是一种将所有逻辑都放在having
子句中的方法:
select PSROLEUSER
from sysadm.PSROLEUSER
group by PSROLEUSER
having sum(case when ROLENAME = 'NCC_Manag' then 1 else 0 end) > 0 and
sum(case when ROLENAME = 'HRM-Content Amin' then 1 else 0 end) > 0;
我喜欢这种方法,因为它非常通用。例如,如果你想要所有'NCC_Manag'
不是的, 'HRM_Content Amin'
你会这样做:
select PSROLEUSER
from sysadm.PSROLEUSER
group by PSROLEUSER
having sum(case when ROLENAME = 'NCC_Manag' then 1 else 0 end) > 0 and
sum(case when ROLENAME = 'HRM-Content Amin' then 1 else 0 end) = 0;
另一种方式:
select X.PSROLEUSER from
(select PSROLEUSER from sysadm.PSROLEUSER where ROLENAME = 'NCC_Manag') X inner join
(select PSROLEUSER from sysadm.PSROLEUSER where ROLENAME = 'HRM-Content Amin') Y
on X.PSROLEUSER = Y.PSROLEUSER
select PSROLEUSER from sysadm.PSROLEUSER where ROLENAME in('NCC_Manag','HRM-Content Amin')
试试这个代码
select PSROLEUSER from sysadm.PSROLEUSER where ROLENAME = 'NCC_Manag'
UNION
select PSROLEUSER from sysadm.PSROLEUSER where ROLENAME = 'HRM-Content Amin'
假设它们返回相同的模式,只需合并它们。
您也可以使用 EXISTS 运算符的另一个版本。
SELECT t1.PSROLEUSER
FROM sysadm.PSROLEUSER t1
WHERE t1.ROLENAME = 'NCC_Manag'
AND EXISTS (
SELECT 1
FROM sysadm.PSROLEUSER t2
WHERE t2.ROLENAME = 'HRM-Content Amin'
AND t1.PSROLEUSER = t2.PSROLEUSER
)
见演示SQLFiddle
select distinct psroleuser from psroleuser where rolename = 'NCC_Manag'
and psroleuser in
(select psroleuser from psroleuser where rolename = 'HRM-Content Amin')