我有以下临时表作为查询的输出:
FacilityID UserID User_Name 1046 105 John Smith 1046 106 John Smith 1046 110 Jack Welsh 1091 107 Ana Romero 1091 248 Rebecca Cruz 1095 418 Alex Sterling
我只需要显示具有相同名称用户的这些设施,并且只有这些名称才能通过查询过滤器。这是为了找出是否有任何设施的用户具有完全相同的名称(即使这些人是不同的人)。因此,考虑到上表,我只需要显示以下内容:
FacilityID UserID User_Name 1046 105 John Smith 1046 106 John Smith
答案 0 :(得分:2)
您可以使用exists
:
select t.*
from t
where exists (select 1
from t t2
where t2.FacilityID = t.FacilityID and t2.user_name = t.user_name and
t2.UserId <> t.userId and
);
如果您有返回结果的查询,那么窗口函数也是一个不错的选择:
with t as (<your query here>)
select t.*
from (select t.*, min(userid) over (partition by FacilityID, user_name) as min_ui,
max(userid) over (partition by FacilityID, user_name) as max_ui
from t
) t
where min_ui <> max_ui;
答案 1 :(得分:2)
我会使用exists
:
select t.*
from table t
where exists (select 1
from table t1
where t1.FacilityID = t.FacilityID and
t1.User_Name = t.User_Name and t.userid <> t1.userid
);
答案 2 :(得分:0)
我会使用EXISTS
子句:
(示例使用CTE [TEMP]作为测试)
;WITH TEMP (FacilityID, UserID, User_Name) AS (
SELECT * FROM (
VALUES
('1046','105','John Smith'),
('1046','106','John Smith'),
('1046','110','Jack Welsh'),
('1091','107','Ana Romero'),
('1091','248','Rebecca Cruz'),
('1095','418','Alex Sterling')
) AS A (Column1, Column2, Column3)
)
SELECT TEMP.*
FROM TEMP
WHERE EXISTS (SELECT 1
FROM TEMP SubT
WHERE SubT.FACILITYID = TEMP.FACILITYID
AND SubT.USER_NAME = TEMP.USER_NAME
AND TEMP.USERID <> SubT.USERID
)
答案 3 :(得分:0)
我将加入我的解决方案:
select FacilityID, UserID, User_Name from (
select FacilityID, UserID, User_Name
count(*) over (partition by User_Name) cnt
from MY_TABLE
) a where cnt > 1