我在写SQL连接查询方面有点新意,我需要帮助加入quires。这是表格。
Table : Txn
TXN_KEY TYPE DATE
--------------------------
111 OD 10/5
221 CS 11/5
112 OD 12/5
222 CS 12/5
Table: TxnAssociation
TXN_KEY REF_TXN_KEY TYPE
---------------------------------
221 111 OS
类型OD
是订单,CS
是客户销售。有一些未结订单,有一些没有订单的销售。
需要连接查询才能获得
之类的输出ORD SAL
--------------
111 221
112 null
null 222
我正在使用德比。我尝试了一些但是不值得调试。任何人都可以帮忙吗...
答案 0 :(得分:1)
SELECT orders.TXN_KEY as ORD,ta.TXN_KEY as SAL
FROM Txn orders
LEFT JOIN TxnAssociation ta ON orders.TXN_KEY = ta.REF_TXN_KEY
WHERE isnull(orders.Type,'OD') = 'OD'
UNION ALL
SELECT NULL as ORD,sales.TXN_KEY as SAL
FROM Txn sales
WHERE sales.Type= 'CS'
AND NOT EXISTS (SELECT 1
FROM Txn s
JOIN TxnAssociation t ON s.TXN_KEY = t.TXN_KEY
AND s.Type= 'CS' AND sales.TXN_KEY = s.TXN_KEY)
这个更好:
SELECT orders.TXN_KEY as ORD,ta.TXN_KEY as SAL
FROM Txn orders
LEFT JOIN TxnAssociation ta ON orders.TXN_KEY = ta.REF_TXN_KEY
WHERE isnull(orders.Type,'OD') = 'OD'
UNION ALL
SELECT ta.REF_TXN_KEY as ORD,sales.TXN_KEY as SAL
FROM Txn sales
LEFT JOIN TxnAssociation ta ON sales.TXN_KEY = ta.TXN_KEY
WHERE sales.Type= 'CS'
AND ta.REF_TXN_KEY is null
答案 1 :(得分:0)
试试这个
SELECT orders.TXN_KEY as ORD, sales.TXN_KEY as SAL
FROM TxnAssociation ta
FULL JOIN Txn orders ON orders.TXN_KEY = ta.REF_TXN_KEY
FULL JOIN Txn sales ON sales.TXN_KEY = ta.TXN_KEY
WHERE isnull(orders.Type,'OD') = 'OD'
AND isnull(sales.Type,'CS') = 'CS'