SQL Server从表1中选择ID,其中table2中的所有ID都符合条件

时间:2017-08-07 15:05:05

标签: sql sql-server

Table1                                 Table2

requestID  requestComplete             requestID   DocumnentNum DocumentComplete
1           0                             1            ABC             1
2           1                             1            DEF             1
3           0                             1            GHI             1
4           0                             2            XXX             1
5           1                             3            YYY             0

我的问题是这样的:如何在表{1}中找到requestID,其中requestComplete = 0的所有文档requestID都有documentCompleted = 1 <body> <div class="tabs"> <div class="tab active">Foo</div> <div class="tab">Bar</div> </div> </body>

4 个答案:

答案 0 :(得分:0)

select t1.requestID
from table1 t1
join table2 t2 on t1.requestID = t2.requestID
where t1.requestComplete = 0
group by t1.requestID
having sum(case when documentCompleted <> 1 then 1 else 0 end) = 0

答案 1 :(得分:0)

SELECT t1.requestID
FROM Table1 t1
WHERE NOT EXISTS (
SELECT * 
FROM Table2 t2
WHERE t1.requestID = t2.requestID
AND t2.DocumentComplete = 0 
) AND t1.requestComplete = 1

答案 2 :(得分:0)

应该像:

SELECT T1.*
  FROM Table1 T1
 WHERE T1.requestComplete = 0
   AND NOT EXISTS (SELECT 1 
                     FROM Table2 T2
                    WHERE T2.requestID = T1.requestID
                      AND T2.DocumentComplete != 1)

答案 3 :(得分:0)

如果T2.DocumentComplete是数值数据类型,你可以这样做。

SELECT t1.RequestID, t1.RequestComplete, t2.MinDoc
FROM Table1 t1
JOIN (SELECT t2.RequestID, MIN(t2.DocumentComplete) AS MinDoc
      FROM Table2 t2
      GROUP BY t2.RequestID
      HAVING MIN(t2.DocumentComplete) = 1) t2 ON t1.RequestID = t2.Requestid
WHERE t1.RequestComplete = 0

如果不是那么你可以将t2.documentcomplete转换为INT。它看起来像这样。

SELECT t1.RequestID, t1.RequestComplete, t2.MinDoc
FROM Table1 t1
JOIN (SELECT t2.RequestID, MIN(CONVERT(INT,t2.DocumentComplete)) AS MinDoc
      FROM Table2 t2
      GROUP BY t2.RequestID
      HAVING MIN(CONVERT(INT,t2.DocumentComplete)) = 1) t2 ON t1.RequestID = 
t2.Requestid
WHERE t1.RequestComplete = 0