2013-04-16 70 views
6

我想在我的where子句中做某種「if」語句。我意識到,SQL不支持這一點,但我相信必須有一些方法使這個工作與SQL語法。正如我用粗體顯示的區域所示,我試圖找到所有以d開頭的項目,並將它們過濾掉,如果它們的userfld2也=容器。做一個「如果」類型的語句在sql where子句

有沒有更合理的方式來做到這一點比我做的還是我的方式離開了商標?

在此先感謝。

Select a.ItemID 
    , b.ConversionFactor VCaseAmt 
    , sum(c.ConversionFactor + 1) SCaseAmt 
    , a.status 
    , a.UserFld2 
From timItem a 
inner join timItemUnitOfMeas b on a.ItemKey = b.ItemKey 
    and b.TargetUnitMeasKey = 115 
left join timItemUnitOfMeas c on a.ItemKey = c.ItemKey 
    and c.TargetUnitMeasKey = 116 
left join timItemUnitOfMeas d on a.ItemKey = d.ItemKey 
    and d.TargetUnitMeasKey = 126 
Where d.TargetUnitMeasKey is null 
    and b.ConversionFactor != c.ConversionFactor + 1 
    and a.Status = 1 
    and **(filter a.itemid not like 'd%' when a.userfld2 = 'Container')** 
Group by a.ItemID, b.TargetUnitMeasKey, b.ConversionFactor, C.TargetUnitMeasKey 
    , c.ConversionFactor, a.status, a.UserFld2 
Order by a.ItemID 
+1

過濾a.itemid不喜歡 'd%' **和** a.userfld2 = '集裝箱'? – NINCOMPOOP

回答

1

使用此:

Select a.ItemID, b.ConversionFactor VCaseAmt, sum(c.ConversionFactor + 1) SCaseAmt, a.status, a.UserFld2 

From timItem a inner join 
    timItemUnitOfMeas b on a.ItemKey = b.ItemKey and b.TargetUnitMeasKey = 115 left join 
    timItemUnitOfMeas c on a.ItemKey = c.ItemKey and c.TargetUnitMeasKey = 116 left join 
    timItemUnitOfMeas d on a.ItemKey = d.ItemKey and d.TargetUnitMeasKey = 126 

Where d.TargetUnitMeasKey is null and b.ConversionFactor != c.ConversionFactor + 1 and a.Status = 1 and 
not (a.itemid like 'd%' AND a.userfld2 = 'Container') 

Group by a.ItemID, b.TargetUnitMeasKey, b.ConversionFactor, C.TargetUnitMeasKey, c.ConversionFactor, a.status, a.UserFld2 

Order by a.ItemID 
+0

賓果。就是這樣。我花了幾個小時試圖讓它工作,令人沮喪。不過非常感謝。 – Aarmora