2016-07-25 58 views
1

,我需要選擇&集團Id & Pid時至少各1個PidIdIsExists=1SQL選擇及集團,如果存在至少一個

Id  Pid  Opt IsExists 
27  2  107 1 
27  2  108 0 
27  5  96  1 
51  9  17  1 
51  9  18  0 
51  10  112 0 
758  25  96  0 
758  97  954 1 
758  194 2902 1 
758  194 2903 1 

結果應該是:

Id IsExists 
27  1  
  • [id=27 | pid=2]的結果&的[id=27 | pid=5]至少有1個與isExists=1

這可能嗎?

+0

您正在使用哪個RDBMS更多? –

+0

我正在使用SQL Server – Eyal

+0

一個ID只能有一個與之關聯的PID嗎?所以對於ID = 27 PID = 2而沒有別的。 – objectNotFound

回答

2

一種方法是使用聚合的兩個級別:

select id 
from (select id, pid, max(isexists) as max_isexists 
     from t 
     group by id, pid 
    ) t 
having count(*) = sum(max_isexists); 

這假定isexists取值爲0和1

的替代僅使用聚合的一個電平,但是有一點麻煩,使用count(distinct)

select id 
from t 
group by id 
having count(distinct pid) = count(distinct case when isexists = 1 then pid end); 
+0

第二個'count'中不需要'distinct'嗎?或者每個分組只有一個? – shawnt00

+0

@ shawnt00。 。 。是。 –

+0

我認爲你的查詢有一個問題(我用第二個)。當Pid = 0時,它只列出一次。我編輯我的問題:對於Id = 758,Pid = 25 IsExists = 0,但是此Id在查詢結果中列出。順便說一句,非常感謝你! – Eyal

1

您需要嵌套聚集:

select Id 
from 
(
    select Id, Pid, 
     -- returns 1 when value exists 
     max(IsExists) as maxExists 
    from tab 
    group by Id, Pid 
) as dt 
group by Id 
    -- check if all Pid got a 1 
having min(maxExists) = 1 
0

嘗試......它採用內組由ID和PID和外一個檢查,以得到IsExists的不同罪名如果有2個或

SELECT ID, 1 as IsExists FROM 
(
    select ID, PID , Count(Distinct IsExists) as IsExists 
    FROM 
    (

     Select 27 as ID , 2 as PID , 1 as IsExists UNION ALL 
     Select 27 as ID , 2 as PID , 0 as IsExists UNION ALL 
     Select 27 as ID , 5 as PID , 1 as IsExists UNION ALL 
     Select 51 as ID , 9 as PID , 1 as IsExists UNION ALL 
     Select 51 as ID , 9 as PID , 0 as IsExists UNION ALL 
     Select 51 as ID , 10 as PID , 0 as IsExists 

    ) a 
    WHERE IsExists = 1 
    Group by ID, PID 
) B 
GROUP BY B.ID 
Having Count(*) >= 2