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

问题描述 投票:-1回答:3

我有两个表,其中包含以下数据:

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

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

我一直在寻找类似的问题,但是找不到这个特定的情况,但是如果有问题,请将我重定向到帖子。

sql sql-server sql-server-2016
3个回答
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

0
投票

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

如果只想为列的每个值得到一个结果,则必须使用group by和aggregation functio,例如min()或max()

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

看你的最后一个样本似乎你正在寻找两个表之间联合的palleid的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 

0
投票

只需在orderid上添加连接条件即可。您在palletid上的加入导致多对多连接,这就是为什么你看到2行,它们实际上是4行(2为orderid 146,2为orderid 142)但是由于你在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
© www.soinside.com 2019 - 2024. All rights reserved.