我需要从提供多行的子查询中选择一个结果

时间:2015-05-25 11:01:09

标签: sql subquery

子查询给出了多个pid但我想选择具有最小到期日的pid 我写的查询是:

SELECT pid, 
       Min(duedate) 
FROM   job 
WHERE  ( pid ) = (SELECT pid 
                  FROM   job 
                  WHERE  job.pending = 'yes' 
                         AND ( pid ) = (SELECT pid 
                                        FROM   machinery_product_bridge 
                                        WHERE  mid = '2')) 

2 个答案:

答案 0 :(得分:0)

在您的评论后编辑

 select j.pid, min(j.duedate) 
 from job j
 where (j.pid) in (select j2.pid from job j2
            where j2.pending='yes' 
            and (j2.pid) in (select pid 
                            from machinery_product_bridge 
                            where mid='2'
                        )
            )
group by j.pid

答案 1 :(得分:0)

最好在子查询中使用Alias。我想你正在寻找这个

select pid, min(j.duedate) 
from job j where (j.pid) in (select jb.pid from job jb
where jb.pending='yes' and (jb.pid)=(select top 1 pid from machinery_product_bridge where mid='2')) 
group by j.PId