SQL连接错过了表中的数据

时间:2017-10-23 01:01:47

标签: sql oracle

我有2张桌子

购买:

socketChannel

产品

PUR#   EID PID  CID          QTY  PTIME     TOTAL_PRICE
--------------------------------------------------------
100001 e01 p002 c001          1 12-AUG-17      211.65
100002 e01 p003 c001          1 20-SEP-17       118.4
100003 e02 p004 c002          5 08-OCT-17        4.95
100005 e04 p007 c004          1 15-OCT-17       119.2
100006 e03 p008 c001          1 12-OCT-17       349.3
100007 e03 p006 c003          2 10-SEP-17       35.91

我必须找到

我能找到的是那些仅按日期购买并计算数量的人,但我不能将产品数量显示为0,因为这些产品在购买时已经过了任何日期。 我希望输出显示所有产品

我的查询:

PID  NAME                   QOH | QOH_THRESHOLD | ORIGINAL_PRICE   DISCNT_RATE
----------------------------------------------------------------------------
p001 stapler                 60            20           9.99          .1
p002 TV                       6             5            249         .15
p003 camera                  20             5            148          .2
p004 pencil                 100            10            .99           0
p005 chair                   10             8          12.98          .3

1 个答案:

答案 0 :(得分:0)

默认情况下,内部联接仅输出具有匹配项的行。要保持行不匹配,在这种情况下需要left join

SELECT COUNT(qty) AS noc, PD.pid, PD.name
FROM   products PD LEFT JOIN purchases P
ON     (PD.pid = P.pid AND P.ptime = 'OCT-17')
GROUP  BY PD.pid, PD.name
ORDER  BY noc DESC;

演示:http://sqlfiddle.com/#!9/1f8e5f/15

进一步阅读:A Visual Explanation of SQL Joins