完全连接具有重复值的两列

Full join in two columns with repeated values

我有两个 table 看起来像这样:

sMinMax:

PartNo  baseID  Min   Max  
11795   1       1     1
11795   5       0     0
11795   6       1     1
01655   65      2     3 

vsStock:

PartNo  baseID  Qty
11795   1       1
11795   1       1
11795   55      1

我想加入他们,所以我得到一个 table,它显示了所有 parNo en 碱基的所有列,如下所示:

结果:

PartNo  baseID  Min   Max  Qty
11795   1       1     1     2
11795   5       0     0     null
11795   6       1     1     null
11795   55      null  null  1
01655   65      2     3     null

所以我只想在两列上使用完整的外部联接来执行此操作,但这会产生与我期望的左联接相同的结果。我尝试了 1000 次,但这是我最后一次尝试:

SELECT 
 a.sPart_ID
,a.uRALBase_ID
,a.MinQty
,a.MaxQty
,b.Qty

FROM [RALNHVTST].[dbo].[sMinMax] as a

FULL OUTER JOIN [RALNHVTST].[dbo].[vsStockList] as b

ON a.sPart_ID = b.sPart_ID
AND a.uRALBase_ID = b.uRALBase_ID
WHERE a.sPart_ID IS NOT NULL
AND a.sPart_ID = 1159

ORDER BY a.sPart_ID

但正如我所说,这给了我与 LEFT JOIN 相同的结果。有人知道我做错了什么吗?

类似的东西?此查询给出了与您预期相同的结果。

SELECT 
 CASE WHEN a.PartNo IS NOT NULL THEN a.PartNo ELSE b.PartNo END AS PartNo
,CASE WHEN a.baseId IS NOT NULL THEN a.baseId ELSE b.baseId END AS baseId
,a.[Min]
,a.[Max]
,SUM(b.Qty) AS Qty

FROM [dbo].[sMinMax] as a

FULL JOIN [dbo].[vsStock] as b

ON a.partNo = b.partNo
AND a.baseId = b.baseId
GROUP BY 
    CASE WHEN a.PartNo IS NOT NULL THEN a.PartNo ELSE b.PartNo END, 
    CASE WHEN a.baseId IS NOT NULL THEN a.baseId ELSE b.baseId END, 
    a.[Min],
    a.[Max]
ORDER BY 
CASE WHEN a.PartNo IS NOT NULL THEN a.PartNo ELSE b.PartNo END

full join 中的过滤很棘手。我建议在子查询中进行过滤和聚合:

SELECT COALESCE(sm.sPart_ID, s.sPart_Id) as sPartId,
       COALESCE(sm.uRALBase_ID, sm.uRALBase_ID
       sm.MinQty, sm.MaxQty, s.Qty
FROM (SELECT sm.*
      FROM [RALNHVTST].[dbo].[sMinMax] sm
      WHERE sm.sPart_ID = 1159
     ) sm FULL OUTER JOIN 
     (SELECT s.sPart_ID, s.uRALBase_ID, SUM(qty) as qty
      FROM [RALNHVTST].[dbo].[vsStockList] s
      WHERE s.sPart_ID = 1159
      GROUP BY s.sPart_ID, s.uRALBase_ID
     ) s
     ON sm.sPart_ID = s.sPart_ID AND
        sm.uRALBase_ID = s.uRALBase_ID
ORDER BY sPart_ID