【问题标题】:check different prices in different tables查看不同表格中的不同价格
【发布时间】:2014-04-23 19:38:57
【问题描述】:

假设我有 3 张桌子:

  1. ITEMS 表(关于项目的所有信息)
  2. ITEM_Pricing(同一商品的多个价格)
  3. 特价(如果我们对某些商品或促销有特价)

我想构建一个查询来检查价格是否存在于 特价 表中,如果不存在则查看 Item_Pricing 表中的价格。换句话说,我想先检查该项目是否存在于特价表中,如果不存在,则检查 item_pricing 表。
这是我试过的,当然没有给出正确答案

select T0.itemcode,T0.ItemName,T0.OnHand,T1.price, T2.Price as Special
from ITEM T0, PRICES T1, S_PRICES T2
where 
    T0.ItemCode=T1.ItemCode
and T0.ItemCode=T2.ItemCode



看起来很简单,但我不知道怎么做??我正在使用 sql server 2008 R2
任何帮助将不胜感激
谢谢。

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    简单规则:只需对from 子句中的逗号说“不”。是时候学习显式的 join 语法,而不是 where 子句中条件的隐式语法。

    如果您使用显式连接编写查询,那么答案将只是“您需要使用left outer join”。你猜怎么着?当条件在where 子句中时,这不容易做到。

    select i.itemcode, i.ItemName, i.OnHand, p.price, sp.Price as Special,
           coalesce(sp.Price, p.price) as ThePriceIWant
    from ITEM i left outer join
         PRICES p
         on p.itemCode = i.ItemCode left outer join
         S_PRICES sp
         on sp.itemCode = i.ItemCode;
    

    注意使用coalesce() 获取所需价格的逻辑。并且使用表缩写作为表别名——它们使查询更容易理解。

    【讨论】:

      【解决方案2】:

      类似的东西

      select      T0.itemcode,T0.ItemName,T0.OnHand,
              IsNull(T2.Price, T1.Price) As Price
      from        ITEM as T0
      left join   PRICES as T1
              on  T1.ItemCode = T0.ItemCode
      left join   S_PRICES as T2
              on  T2.ItemCode = T0.ItemCode
      

      假设有零个或一个 SpecialPrice 和零个或一个价格

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-29
        • 1970-01-01
        • 2021-05-26
        • 2021-03-11
        • 2014-01-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多