2016-10-27 1 views
1

Ich möchte eine Ansicht von 2 Tabellen mit einer Art von bedingten Join erstellen (Entschuldigung meine Ignoranz, wie ich SQL-Codierung neu bin!). Die beiden Tabellen sind wie folgt:Ansicht erstellen mit Join-Bedingungen

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 

Wo ich mit der Syntax habe Schwierigkeiten ist, dass TABLE2 entweder einen Preis auf Filialebene hat (z. B. S001) oder auf nationaler Ebene (z. B. SNAT) oder gar kein Preis.

Erforderlich Ausgabe anzeigen:

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) 

Mein aktueller Code wie unten aussieht ... Ich weiß nur nicht, wo/wie die Regeln für „wenn kein Speicher bestimmten Preis hinzufügen, SNAT verwenden, sonst 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 

Antwort

0

Ich würde beitreten tabelle1 mit tabelle1 zweimal, einmal für die Filialebene und erneut für die nationale Ebene und zeige nur die nationale Ebene, wenn die Speicherebene existiert nicht:

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' 
+1

Danke für die schnelle Antwort! Das hat den Trick gemacht :) – Anton

0

Sie möchten mehrere 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 
+0

Vielen Dank für die schnellen Antwort! Das hat den Trick gemacht :) – Anton

Verwandte Themen