在两列中完全连接并重复值

时间:2019-12-06 09:31:59

标签: sql tsql join where-clause outer-join

我有两个看起来像这样的表:

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

我想加入他们,所以我得到了一个表格,该表格将所有parNo的基础显示为所有列,如下所示:

结果:

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相同的结果。有人知道我在做什么错吗?

2 个答案:

答案 0 :(得分:2)

类似的东西?该查询给我的结果与您预期的相同。

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

答案 1 :(得分:0)

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