如何从两个表中选择记录,COALESCE表1中不存在的值

时间:2019-04-11 18:54:35

标签: sql sql-server sql-server-2016

我有两个包含以下数据的表:

table1 (palletid, caseshipped, orderid)

palletid   |  (caseshipped)  | orderid
2002057    |    10.00        |  146
2002058    |    50.00        |  146
2002059    |    25.00        |  146
2002058    |    10.00        |  142 

table2 (palletid,caseshipping, orderid)

palletid   |  (caseshipping)  |  orderid
2002055    |    0.00          |    146
2002056    |    25.00         |    146
2002057    |    10.00         |    146
2002058    |    50.00         |    146
2002059    |    25.00         |    146
2002060    |    75.00         |    146
2002058    |    10.00         |    142

查询tableresult(DISTINCT(table2.palletid),COALESCE(table1.caseshipped,0), orderid的预期结果

palletid   |  (caseshipped)  | orderid
2002055    |    0.00         |  146
2002056    |    0.00         |  146
2002057    |    10.00        |  146 
2002058    |    50.00        |  146
2002059    |    25.00        |  146
2002060    |    0.00         |  146

我有以下查询,但是重复table2.palletid和错误的table1.caseshipped和错误的table2.orderid

SELECT DISTINCT table2.palletid, 
COALESCE(table1.caseshipped,0) FROM table2
LEFT JOIN table1 ON table2.palletid=table1.PalletID
WHERE table2.orderid = 146

查询结果:

palletid   |  (caseshipped) | orderid
2002055    |    0.00        |   146
2002056    |    0.00        |   146
2002057    |    10.00       |   146
2002058    |    10.00       |   146       Value should not appear(orderid=142)
2002058    |    50.00       |   146       
2002059    |    25.00       |   146
2002060    |    0.00        |   146

如何更正查询以获得预期结果?为什么我会得到重复的结果?

我一直在寻找类似的问题,但找不到这种具体情况,但是如果有人提出这个问题,请直接将我重定向到该帖子。

3 个答案:

答案 0 :(得分:1)

您只是在ON子句中缺少一个条件。.

SELECT DISTINCT table2.palletid, 
COALESCE(table1.caseshipped,0) FROM table2
LEFT JOIN table1 ON table2.orderID = table1.orderID AND table2.palletid=table1.PalletID
WHERE table2.orderid = 146

答案 1 :(得分:0)

您没有在结果中重复结果。.在SQL中,distingle子句适用于行中的每个值,而不是单个列值

如果只希望为列的每个值提供结果,则必须使用分组和聚集功能,例如min()或max()

SELECT  table2.palletid, 
max(COALESCE(table1.CaseCount,0)) 
FROM table2
LEFT JOIN table1 ON table2.palletid=table1.PalletID
GROUP BY table2.palletid

寻找最后一个样本似乎是根据两张表之间的并列来查找min()组

selet  palletid,  min(caseshipped), orderid
from(
  select  palletid,  caseshipped, orderid
  from table1
  union  
  select  palletid,  caseshipped, orderid
  from table1
) t  
where orderid = 145 
group by palletid 

答案 2 :(得分:0)

只需在 orderid 上添加加入条件。您对Palletid的联接导致了多对多联接,这就是为什么您看到2行,它们实际上是4行(对于Orderid 146为2行,对于Orderid 142为2行),但是由于您在Orderid 146上具有过滤器,因此您仅看到2行。试试这个:

SELECT DISTINCT table2.palletid,
COALESCE(table1.caseshipped,0), table2.orderid FROM table2
LEFT JOIN table1 
  ON table2.palletid=table1.PalletID
  AND table2.orderid = table1.orderid
WHERE table2.orderid = 146