2014-02-05 36 views
-1

在T-SQL 2008 R2中,我試圖確定如何設置SQL完成以下 目標:T-SQL 2008 R2 where語句與幾個不是項目

SELECT table1.customer_id, 
     type, 
     start_date, 
     end_date, 
     program_id 
FROM table1 
     JOIN table2 
     ON table1.customer_id = table2.customer_id 
  1. 其中type不=('aa','cc')並輸入not ='g2',其中code = 3 在table1中,每個customer_id都有很多記錄,並且可能有大量各種類型的值。我只想要不包含 上面列出的值的customer_id。 和
  2. table2只有一個customer_id。 Customer_id是table2的關鍵。 我希望客戶在3列之一中沒有值: start_date,end_date和program_id。

上面列出的第1部分和第2部分對於要選擇的customer_id都必須爲true。 因此,你可以告訴我如何設置該SQL?

+0

請出示樣本數據和預期的結果,而不是文字問題。 –

+0

請告訴我你沒有2個值存儲在Type的一個單元格中(在同一個單元格中,例如'.a','cc'?)。如果你這樣做會破壞標準化。 –

+0

@Jason我想他想要做的是'(不要輸入('aa','cc')或(type <>'g2'和code = 3)' –

回答

1

我無法準確地告訴你,因爲我看不到你的數據庫結構,但我相信它會是這樣的:

SELECT table1.customer_id,type,start_date,end_date,Program_id 
    FROM table1 JOIN table2 ON table1.customer_id = table2.customer_id 
    WHERE (table1.type NOT IN('aa', 'cc', 'g2') AND table1.code = 3) 
    AND (table2.start_data IS NULL OR table2.end_date IS NULL OR table2.program_id IS NULL) 
+0

你的查詢不考慮類型<>'g2' – Jayvee

+0

好點。我編輯它包括:) –

0

給支票傑森(+1),但我會拉條件爲加盟
有時可以幫助查詢優化器

SELECT table1.customer_id,type,start_date,end_date,Program_id 
    FROM table1 
    JOIN table2 
    ON table1.customer_id = table2.customer_id 
    AND table1.type NOT IN ('aa', 'cc') 
    AND (table1.code = 3 and table1.type <> 'g2') 
    AND (table2.start_data IS NULL OR table2.end_date IS NULL OR table2.program_id IS NULL) 

我得到這個是你是從字面上要求的,但它是不是你認爲它是

AND table1.type NOT IN ('aa', 'cc') 
AND (table1.code = 3 and table1.type <> 'g2') 

相同

AND table1.type NOT IN ('aa', 'cc') 
AND table1.type <> 'g2' 
AND table1.code = 3 

相同

AND table1.type NOT IN ('aa', 'cc', 'g2') 
AND table1.code = 3 

我想你的意思是要問什麼是一樣的東西

AND ( table1.type NOT IN ('aa', 'cc') 
     or (table1.code = 3 and table1.type <> 'g2') 
    ) 
0

如何欲以INNER JOIN:

SELECT table1.customer_id,type,start_date,end_date,Program_id 
    FROM table1 
INNER JOIN table2 ON table1.customer_id = table2.customer_id 
    WHERE table1.type != 'aa' 
    AND table1.type != 'cc' 
    AND table1.type != 'g2' 
    AND table1.code = 3 
    AND (table2.start_data IS NULL OR table2.end_date IS NULL OR table2.program_id IS NULL) 

讓我知道它是否可以正常工作!

Regrads, ANDOURA

+0

這看起來很接近。然而table1.code = 3只適用於type ='g2' – user1816979

+0

非常感謝! – user1816979

+0

希望它給你解決你的問題:) – Ando