2014-09-11 82 views
0

我有2個兩個表,顯示重複SQL與在

Invoice (ordernumber, status(which assign to InvoiceStatuses), etc) 

InvoiteStatuses(status name, statusid) 

我需要檢查發票副本只爲訂單編號,但where status != statusID(其中名稱爲「取消」)

SELECT A.* 
FROM Invoices A 
JOIN InvoiceStatuses b 
(
    SELECT * FROM InvoiceStatuses 
    WHERE InvoiceStatus = 'CANCELLED' 
) B 
ON A.InvoiceStatus!=b.InvoiceStatusID 
WHERE exists (SELECT OrderNumber 
    FROM Invoices c 
    WHERE a.OrderNumber = c.OrderNumber 
    GROUP BY OrderNumber 
    HAVING COUNT(*)>1) 
+2

請寫出你想要做什麼樣的文字說明,而不是隻寫你想要的話在英語中WHERE子句。目前還不完全清楚你想在這裏做什麼。 – 2014-09-11 10:14:14

+0

你在'invoices'表中有主鍵列嗎? – Bulat 2014-09-11 10:29:46

+0

是的,我擁有它。 – NoNameR 2014-09-11 10:34:48

回答

0

我認爲您需要在您的查詢中進行以下更改

JOIN子句過濾取消狀態出來,where子句只檢索複製

SELECT A.* 
FROM Invoices A 
WHERE exists (SELECT OrderNumber 
       FROM Invoices c 
       JOIN InvoiceStatuses b 
       ON c.InvoiceStatus=b.InvoiceStatusID 
        AND InvoiceStatus != 'CANCELLED' 
       WHERE a.OrderNumber = c.OrderNumber 
       GROUP BY OrderNumber 
       HAVING COUNT(*)>1) 
+1

這將返回記錄作爲重複,即使沒有其他記錄匹配 - 'InvoiceStatus!='CANCELLED'' – Bulat 2014-09-11 10:31:45

+0

但如果我有例如:兩個發票號碼相同,但一個被取消第二不 - 不需要顯示它。在你查詢它的節目 – NoNameR 2014-09-11 10:33:14

+0

我已更新查詢。你可以檢查這是否有效? – 2014-09-11 11:04:39