2017-05-08 183 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

它會隨機 –