我想显示/显示每次交易是否找到产品。
tblProducts
ID PRODCODE PRODDESC
1 PFX-321 MILK CHOCO
2 PDF-875 COFFEE JELLY
3 PWA-718 MILK SHAKE
tblTransactions
TCODE PRODCODE
BMX2213391 PFX-321
BMX2213391 PDF-875
PDFSD92851 PDF-875
我希望结果显示如下
TCODE PRODCODE FOUND
BMX2213391 PFX-321 YES
BMX2213391 PDF-875 YES
BMX2213391 PWA-718 NO
PDFSD92851 PFX-321 NO
PDFSD92851 PDF-875 YES
PDFSD92851 PWA-718 NO
我试过,INNER JOIN,FULL OUTER JOIN,LEFT JOIN和RIGHT JOIN但是我没有得到我需要的确切数据。
以下是我测试的查询。
SELECT * FROM tblProducts a INNER JOIN tblTransactions b ON a.PRODCODE = b.PRODCODE
SELECT * FROM tblProducts a FULL OUTER JOIN tblTransactions b ON a.PRODCODE = b.PRODCODE
SELECT * FROM tblProducts a LEFT JOIN tblTransactions b ON a.PRODCODE = b.PRODCODE
SELECT * FROM tblProducts a RIGHT JOIN tblTransactions b ON a.PRODCODE = b.PRODCODE
答案 0 :(得分:1)
我非常确定这是有效的 - SQLFiddle在这里:http://sqlfiddle.com/#!3/65eb1/23
WITH AllVals AS
(SELECT a.PRODCODE, b.TCODE
FROM tblProducts a
CROSS JOIN tblTransactions b)
SELECT DISTINCT c.PRODCODE,
c.TCODE,
CASE WHEN d.PRODCODE IS NULL THEN 'NO' ELSE 'YES' END AS FOUND
FROM AllVals c
LEFT OUTER JOIN tblTransactions d
ON c.PRODCODE = d.PRODCODE
AND c.TCODE = d.TCODE
答案 1 :(得分:1)
http://sqlfiddle.com/#!3/65eb1/24
select DT.TCODE, DT.PRODCODE, case when (Tr2.TCODE IS null and Tr2.PRODCODE IS null) then 'No' else 'Yes' END as FOUND
from tblTransactions Tr2 right join
(
select distinct Tr.TCODE, p.PRODCODE
from tblProducts p cross join tblTransactions Tr
) DT
on DT.PRODCODE = Tr2.PRODCODE and DT.TCODE = Tr2.TCODE;