SQL select&如果存在至少一个,则分组

时间:2016-07-25 22:10:39

标签: sql sql-server

我需要选择&小组Id& Pid Pid中每IdIsExists=1至少有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]&amp;的结果对于isExists=1至少有1 <script type="text/javascript"> $(document).ready(function(){ var d = new Date(); var returnFromServer = var dateStr = d.toString() $.post(window.location, { dateStr: dateStr }).success(function(data){ //this is return from server alert(data); }); alert(dateStr); }); </script> <div id="divMessage"> <?php $dstr = 'nothing!'; if(isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0) $dstr = $_POST["dateStr"]; $v = 'current date/time is '.$dstr; echo "<span style=\"color:green\">$v</span>"; ?> </div>

有可能吗?

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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

答案 2 :(得分: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