连接 SQL 中行不均匀的表而不重复

Joins tables in SQL with uneven rows without duplication

我在 SQL 服务器 GRVGIV 中有两个 table 具有这些列:

查询如下:

select 
    GRV.ProductID, GRV.ProductName, GRV.Unit, GRV.ReceivedQTY,
    GIV.ProductID, GIV.ProductName, GIV.Unit, GIV.Quantity
from 
    GRV
full outer join 
    GIV on GRV.ProductID = GIV.ProductID

这就是我得到的:

问题是红色字体的行实际上并不在我的 GIV table 中。我想要的只是 table 的实际数据应该按原样组合。 GRV 在右侧,GIV 在左侧,没有偶数行表示 null

有没有可用的选项?我需要它来创建库存分类帐的原因 Crystal 报告,我可以在其中显示所有收到和发出数量的交易日期,并最终生成期末余额。请在这方面帮助我。

您的问题缺少明确的“预期结果”。

以下选项可能对您有所帮助。

示例数据

create table ItemIssued
(
  ProductId nvarchar(5),
  Quantity int
);
insert into ItemIssued (ProductId, Quantity) values
('P0001', 100),
('P0002',  50),
('P0004',   1);

create table ItemReceived
(
  ProductId nvarchar(5),
  Quantity int
);
insert into ItemReceived (ProductId, Quantity) values
('P0002',  55),
('P0003', 200);

解决方案 1

null.

select i.ProductId as ProductId,
       i.Quantity as Quantity,
       r.ProductId as ProductId,
       r.Quantity as Quantity
from ItemIssued i
full join ItemReceived r
  on r.ProductId = i.ProductId;

解决方案 2

没有null.

select coalesce(i.ProductId,'') as ProductId,
       coalesce(convert(nvarchar(5), i.Quantity),'') as Quantity,
       coalesce(r.ProductId,'') as ProductId,
       coalesce(convert(nvarchar(5), r.Quantity),'') as Quantity
from ItemIssued i
full join ItemReceived r
  on r.ProductId = i.ProductId;

解决方案 3

相邻的桌子。

with ctei as
(
  select row_number() over(order by i.ProductId) as RowNum,
         i.ProductId,
         i.Quantity
  from ItemIssued i
),
cter as
(
  select row_number() over(order by r.ProductId) as RowNum,
         r.ProductId,
         r.Quantity
  from ItemReceived r
)
select ctei.ProductId,
       ctei.Quantity,
       cter.ProductId,
       cter.Quantity
from ctei
full join cter
  on cter.RowNum = ctei.RowNum;

解决方案 4

所有有数量的产品。

with cte as
(
  select i.ProductId
  from ItemIssued i
    union
  select r.ProductId
  from ItemReceived r
)
select c.ProductId,
       i.Quantity,
       r.Quantity
from cte c
left join ItemIssued i
  on i.ProductId = c.ProductId
left join ItemReceived r
  on r.ProductId = c.ProductId;

结果

与解决方案的顺序相同。

Fiddle 观看实际效果。