2017-08-07 83 views
-1
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 

我的問題所有的ID是:我如何找到一個表,其中requestComplete = 0和所有在表2是requestID的文件已經documentCompleted = 1requestID的?從表1中的SQL Server選擇ID其中,表2中的比賽標準

+0

您的預期結果是什麼? –

+0

對於特定的請求,表2中是否有可能沒有記錄? –

回答

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 
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 
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) 
+0

「!=」只是T-SQL,這對於堅持多平臺[ANSI 99 SQL標準](http://web.cecs.pdx.edu/~len/sql1999.pdf)更好,並使用「<= >「代替。雖然他們都在SQL Server下工作,並且都給出了相同的結果,加上「<>」字符在鍵盤上彼此更接近:) –

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 
相關問題