2012-11-28 19 views
1

我需要確定表中的其他項的哪些項目,也存在於ItemMain中,哪些項目沒有。忽略查詢兩側的第一個'0'

問題是一些UPC在開始時有0,有些沒有。

所以我試過這個查詢,但結果不好看。

SELECT * from OtherItems 
WHERE UPC like '0%' and upc not in(select '0' + UPC from itemmain) 
Or UPC not in(select UPC from itemmain)) 

有人能指導我做什麼我做錯了嗎?

+0

缺失括號? – 2012-11-28 18:49:58

+0

你應該真的嘗試修復你的數據,如果你有這個問題,你需要在你使用它的地方照顧它,而不是現在修復它,一勞永逸。 –

+0

好的我會解決它。但現在我需要這個查詢儘快。 – Ezi

回答

3
select * 
from OtherItems 
where not exists (select * 
        from itemmain 
        where UPC=OtherItems.UPC or '0'+UPC=OtherItems.UPC) 

或者是:

select * 
from OtherItems 
where (UPC like '0%' 
     and not exists (select * from itemmain where '0'+UPC=OtherItems.UPC)) 
    or (UPC not like '0%' 
     and not exists (select * from itemmain where UPC=OtherItems.UPC)) 
+0

我不知道爲什麼,但我得到了很多實際上存在於itemmain中的項目 – Ezi

+0

我們做了很多假設:也許最好是發佈最小的'create table'語句? – 2012-11-28 19:06:51

+1

也發佈了一個既存在又正在返回的例子,這可能也有幫助。 – 2012-11-28 19:07:52

0

你的邏輯需要括號圍繞OR:

SELECT * from OtherItems 
WHERE UPC like '0%' and 
    (upc not in(select '0' + UPC from itemmain) 
    Or UPC not in(select UPC from itemmain)) 

與斗拱,並且優先,讓你有效地得到(A AND B) OR C

+0

不應該第一個'('先走一點?也許我不能算,但它們匹配嗎? – 2012-11-28 19:08:58

+0

@jack我只是添加了abracket到那裏,但你是對的 - 太多了關於邏輯,誰知道,但有*可能*是一個像這樣的錯誤 – Bohemian

3

UPC通常沒有alpha通道在他們的字符。爲什麼不把它們轉換成一個數字來消除前導零,如果它存在於一個而不是另一個?

SELECT * 
FROM OtherItems A 
WHERE NOT EXISTS 
    (SELECT 1 
     FROM ItemMain B 
     WHERE CAST(A.UPC as DECIMAL(18)) = CAST(B.UPC) AS DECIMAL(18)) 
+1

+1(特別是'不存在'),但我要提醒的是,即使我們知道關於UPCs,我們什麼也不知道關於OPs數據如何受到限制! – 2012-11-28 19:02:28

+0

它是一個好主意,不幸的是我們確實有一些upc與字符 – Ezi

+0

Bollocks。有這樣的計劃。 –