在sql where子句中执行“if”类​​型语句

时间:2013-04-16 18:09:45

标签: sql

我正在尝试在where子句中执行某种“if”语句。我意识到sql不支持这个,但我确信必须有一些方法可以使用sql语法。如我粗体区域所示,我试图找到以d开头的所有项目,如果他们的userfld2也是容器,则将其过滤掉。

有没有一种比我正在做的更合理的方法呢?或者我是否会离开标记?

提前致谢。

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 个答案:

答案 0 :(得分: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