2013-10-22 82 views
0

我需要在表中找到具有0保費的策略,但如果具有相同保單號的另一個策略具有保費,則不需要。這裏是我的僞代碼:查詢其他記錄的SQL子查詢語法

select * from tblPolicies where premium = 0 
(but not if anther record has the same policyNumber and premium <> 0) 

我知道這是可怕的,但我迷路了,這是我能拿出最好的!

回答

1

可能的查詢1:

SELECT M.* FROM tblPolicies AS M 
WHERE premium = 0 AND policyNumber NOT IN 
(
    SELECT S.policyNumber 
    FROM tblPolicies AS S 
    WHERE S.policyNumber = M.policyNumber 
    AND S.premium <> 0 
) 

可能的查詢2:

SELECT SA.* FROM 
(
    SELECT M.* FROM tblPolicies AS M 
    WHERE premium = 0 
) AS SA 
INNER JOIN tblPolicies AS SB 
ON SA.policyNumber = SB.policyNumber 
WHERE SB.premium <> 0 

可能的查詢3:

SELECT * FROM tblPolicies AS SA 
INNER JOIN tblPolicies AS SB 
ON SA.policyNumber = SB.policyNumber 
WHERE SA.premium = 0 AND SB.premium <> 0 
+0

+1很好的回答。人們也可以使用「NOT EXISTS」。 –

+0

這工作,我很欣賞它,但它是非常慢...無論如何,以提高性能? – daytonk

+0

你有關於policyNumber的索引嗎?另外,表中有多少條記錄?它是什麼DBMS(SQL Server,MySQL,MS Access等)? – Linger

1
select p_no from 
(select p_no, sum(premium) as tot_prem from policy group by p_no) as pol 
where tot_prem>0; 

p_no->premium_no

策略 - >策略表