如果首选值为null,则返回另一个值

时间:2013-06-19 10:55:47

标签: sql

SQL noob在这里挣扎于查询...

我有两个表,一个包含产品信息(ItemCode,ItemName),另一个包含每个产品的不同价目表(最多10个)。

用简单的英语,这就是我想要实现的目标:

Select T0.ItemCode, T0.ItemName, T1.Price

从价目表6中获取价格:如果价格表6中的价格为空,则从价格表1中扣除价格并扣除5%

看起来它应该是相当直接但我不确定从哪里开始说实话我会感激一些建议。

非常感谢, 迈克尔

2 个答案:

答案 0 :(得分:1)

以下是一种使用两个连接执行此操作的方法,每个连接一个:

 select pi.ItemCode, pi.ItemName,
        coalesce(pl6.price, pl1.price*0.95) as price
 from ProductInformation pi left outer join
      PriceList pl6
      on pi.ItemCode = pl6.ItemCode and pi6.List = 6 left outer join
      PriceList pl1
      on pi.ItemCode = pl1.ItemCode and pi1.list = 1;

这假设价格表位于不同的行上。如果它们位于同一行(price1price2 ...),那么这将有效:

 select pi.ItemCode, pi.ItemName,
        coalesce(pl.price6, pl.price1*0.95) as price
 from ProductInformation pi left outer join
      PriceList pl
      on pi.ItemCode = pl.ItemCode;

答案 1 :(得分:0)

您需要coalesce功能,如下所示:

SELECT COALESCE(T1.PRICE,"MISSING") FROM [TABLE]

您可以在RDBMS的文档中找到有关它的更多信息,但如果该字段返回NULL,则会返回“missing”。