2016-07-25 65 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