我不确定如何完成我想要做的事情。这是一个简化版本:
CREATE TABLE PO (
POID int,
PONumber varchar(20)
)
INSERT INTO PO
(POID, PONumber)
VALUES (1, '2520001')
CREATE TABLE WSR (
WSRID int,
POID int,
WSRNumber varchar(1)
)
INSERT INTO WSR
(WSRID, POID, WSRNumber)
VALUES (1, 1, '1')
INSERT INTO WSR
(WSRID, POID, WSRNumber)
VALUES (2, 1, '2')
CREATE TABLE Invoice(
InvoiceID int,
POID int,
InvoiceNumber varchar(20)
)
INSERT INTO Invoice
(InvoiceID, POID, InvoiceNumber)
VALUES (1, 1, '11111111')
INSERT INTO Invoice
(InvoiceID, POID, InvoiceNumber)
VALUES (2, 1, '11111111 C010001')
INSERT INTO Invoice
(InvoiceID, POID, InvoiceNumber)
VALUES (3, 1, '11111111 H010001')
INSERT INTO Invoice
(InvoiceID, POID, InvoiceNumber)
VALUES (4, 1, '11111111 Q010001')
INSERT INTO Invoice
(InvoiceID, POID, InvoiceNumber)
VALUES (5, 1, '22222222')
CREATE TABLE InvoiceMatch(
POID int,
InvoiceID int,
WSRID int)
INSERT INTO InvoiceMatch
(POID, InvoiceID, WSRID)
VALUES (1, 1, 1)
INSERT INTO InvoiceMatch
(POID, InvoiceID, WSRID)
VALUES (1, 5, 2)
根据该数据,我希望能够得到这个结果:
PONumber, WSRNumber, InvoiceNumber
2520001 1 11111111
2520001 NULL 11111111 C010001
2520001 NULL 11111111 H010001
2520001 NULL 11111111 Q010001
2520001 2 22222222
我目前使用的查询是:
SELECT DISTINCT p.POID, p.PONumber, w.WSRNumber, i.InvoiceNumber
FROM PO p
LEFT OUTER JOIN InvoiceMatch im ON im.POID = p.POID
LEFT OUTER JOIN WSR w ON w.POID = im.POID
LEFT OUTER JOIN Invoice i ON i.POID = im.POID
WHERE p.PONumber = '2520001'
但这不正确。所有WSR都链接到每个发票。帮助
答案 0 :(得分:2)
试试这个:
SELECT DISTINCT p.POID
,p.PONumber
,w.WSRNumber
,i.InvoiceNumber
FROM PO p INNER JOIN Invoice i
ON i.POID = p.POID LEFT JOIN InvoiceMatch im
ON i.InvoiceID = im.InvoiceID LEFT OUTER JOIN WSR w
ON im.WSRID = w.WSRID
WHERE p.PONumber = '2520001'
答案 1 :(得分:1)
我认为您的某些Left Outer Joins
中的表格顺序可能已关闭:
SELECT DISTINCT p.POID, p.PONumber, w.WSRNumber, i.InvoiceNumber
FROM PO p
LEFT OUTER JOIN InvoiceMatch im ON p.POID = im.POID
LEFT OUTER JOIN WSR w ON im.POID = w.POID
LEFT OUTER JOIN Invoice i ON m.POID = i.POID
WHERE p.PONumber = '2520001'
或者将上一个查询中的联接切换为Right Outer Joins
而不是左。