我想从2个表中创建一个带有某种条件连接的视图(请原谅我的无知,因为我是SQL编码的新手!)。这两个表如下:
TABLE1
Store | Product | MAC Price
S001 | 123 | 15.00
S001 | 456 | 17.50
S002 | 123 | 16.00
S002 | 456 | 17.50
S002 | 789 | 20.00
TABLE2:
Store | Product | SELL Price
S001 | 123 | 25.00
S001 | 456 | 27.50
S002 | 123 | 26.00
SNAT | 123 | 35.00
SNAT | 456 | 40.00
我在语法上苦苦挣扎的是,TABLE2要么在商店级别(例如S001)或国家级别(例如SNAT)有价格,要么根本没有价格。
必需的观看输出:
Store | Product | MAC Price | Sell Price
S001 | 123 | 15.00 | 25.00
S001 | 456 | 17.50 | 25.00
S002 | 123 | 16.00 | 26.00
S002 | 456 | 17.50 | 40.00 (no Store specifc, therefore SNAT)
S002 | 789 | 20.00 | 0.00 (no Store specifc or SNAT)
我目前的代码如下所示......我只是不知道在哪里/如何添加规则"如果没有特定商店的价格,请使用SNAT,否则为0.00" ...
create view SCH.Z_MAC_PRICE as
select SCH.table1.store, SCH.table1.product, SCH.table1.mac,
SCH.table2.sell
from SCH.table1 left outer join
SCH.table2
on SCH.table1.store = SCH.table2.store and
SCH.table1.product = SCH.table2.product
答案 0 :(得分:0)
您需要多个left join
s:
create view SCH.Z_MAC_PRICE as
select t1.store, t1.product, t1.mac,
coalesce(t2s.sell, t2n.sell, 0) as sell
from SCH.table1 t1 left outer join
SCH.table2 t2s
on t2s.store = t1.store and
t2s.product = t1.product left outer join
SCH.table2 t2n
on t2s.store = 'SNAT' and
t2s.product = t1.product
答案 1 :(得分:0)
我将table1加入table1 两次,一次用于商店级别,再次用于国家级别,并且仅在商店级别不存在时才显示国家级别:
CREATE VIEW z_mac_price AS
SELECT t1.store,
t1.product,
t1.mac_price,
COALESCE(t2store.sell_price, t2nat.sell_pirce, 0.00)
FROM table1 t1
LEFT JOIN table2 t2store ON t2store.product = t1.product AND
t2store.store = t1.store
LEFT JOIN table2 t2nat ON t2nat.product = t1.product AND
t2nat.store = 'SNAT'