2017-05-08 30 views
0

假设我有一个表empgroupinfo,我想取得只有来自这两个groupId 500 and 501(将动态地来)的employeeid,不应该在更多或更少的组数,empid != 102这是在500组。Postgresql:查询返回不正确的数据

我曾尝试以下查询:

select empid from empgroupinfo 
where empgroupid in(500,501) and empid != 102 
group by empid having count(empid) = 2 

但是这上面的查询也返回EMPID是其他组。

我想获取empid的情况下,员工只有这两个groupid(500和501)和empid != 102

回答

1

WHERE子句选择行,其中empgroupid是500或501,而不是empid S其中所有empgroupid S型阵列[500, 501]

您可以在HAVING子句中使用ARRAY_AGG

SELECT empid 
FROM empgroupinfo 
GROUP BY empid 
-- ORDER BY clause here is important, as array equality checks elements position by position, not just 'same elements as' 
HAVING ARRAY_AGG(DISTINCT empgroupid ORDER BY empgroupid) = ARRAY[500, 501] 

具体情况取决于[500, 501]阵列从何而来,你可能不知道自己是否是排序或不。在这种情况下,“包含AND包含于”(运营商@><@)也应该起作用。


#= CREATE TABLE empgroupinfo (empid int, empgroupid int); 
CREATE TABLE 
Time: 10,765 ms 

#= INSERT INTO empgroupinfo VALUES (1, 500), (1, 501), (2, 500), (2, 501), (2, 502); 
INSERT 0 5 
Time: 1,451 ms 

#= SELECT empid 
    FROM empgroupinfo 
    GROUP BY empid 
    HAVING ARRAY_AGG(empgroupid ORDER BY empgroupid) = ARRAY[500, 501]; 
┌───────┐ 
│ empid │ 
├───────┤ 
│  1 │ 
└───────┘ 
(1 row) 

Time: 0,468 ms 
+0

@BunkerBoy:恐怕我不明白你的编辑。如果你不想'empId = 102',只需在查询中添加一个'WHERE empId <> 102'。 – Marth

+0

对不起,我犯了一个错误,它不是关于empid!= 102谢谢我现在纠正了谢谢,它为我工作.. –

+0

告诉我一件事假设,如果我的groupids是400和345所以我将不得不按阵列顺序排列我的数组根据查询? –

0

尝试:

select empid 
from empgroupinfo 
group by empid 
where empid <> 102 
having count(*) = 2 and min(empgroupid) = 500 and max(empgroupid) = 501 
+0

empgroupid是动态的 –

+0

有用于empgroupid只有两个可能值?它们总是连续的吗?你能举出更多的例子吗? – Renzo

+0

它会随机 –