合并两个表中的结果到1个公共列

时间:2019-11-01 14:54:47

标签: sql-server sql-server-2016

我们有一些仓库,我们会定期进行盘点。

我需要报告(目标是使用Microsoft PowerBi)以显示同一仓库(位置)的不同库存之间的差异,但唯一的共同栏是仓库编号。

“产品”列是动态的:它可能出现在一个库存上,而不是另一个上(这正是我们需要知道的)

每个库存都在不同的表上,如下所示:

TABLE A     
LOCATION    PRODUCTS           QTY
WH 1        PRODUCT NO. 1      10
WH 1        PRODUCT NO. 2      100
WH 1        PRODUCT NO. 333    5
WH 2        PRODUCT NO. YYY    22

TABLE B     
LOCATION    PRODUCTS            QTY
WH 1        PRODUCT NO. 1       10
WH 1        PRODUCT NO. 2       100
WH 1        PRODUCT NO. 333     5
WH 1        PRODUCT NO. XXX     77
WH 2        PRODUCT NO. YYY     45
WH 1        PRODUCT NO. YYY     555
WH 2        PRODUCT NO. 1       14

预期的输出应如下所示:

Location    products           QTY A    QTY B
WH 1        PRODUCT NO. 1      10       10
WH 1        PRODUCT NO. 2      100      100
WH 1        PRODUCT NO. 333    5        5
WH 1        PRODUCT NO. XXX    -        77
WH 1        PRODUCT NO. YYY    -        555
WH 2        PRODUCT NO. 1      -        14
WH 2        PRODUCT NO. YYY    22       45

我已经阅读了有关FULL OUTER JOIN和PIVOT TABLES的信息,但我无法完全理解和使用它们(而且我也不确定它们是否是这里的目标)。

SQL版本是Microsoft SQL Server 2016 Standard

3 个答案:

答案 0 :(得分:2)

一个选择是Union ALLPIVOT或条件聚合一起使用

示例

Select *
 From  (
        Select Location
              ,Products
              ,Qty
              ,Col = 'Qty A'
         From  Table A
        Union All
        Select Location
              ,Products
              ,Qty
              ,Col = 'Qty B'
         From  Table B
       ) src
 Pivot (sum(Qty) for Col in ([Qty A],[Qty B] ) ) pvt

答案 1 :(得分:1)

这不是简单的完全联接吗?我想念什么吗?此处似乎不需要枢轴。

select isnull(A.location,B.location) location, isnull(A.products, B.products) products,
   A.QTY A_QTY, B.QTY B_QTY
from tableA A
full outer join tableB B
   on A.location = B.location
   and A.products = B.products

A_QTY或B_QTY如果在一个表中而不在另一个表中,则为null。

答案 2 :(得分:0)

尝试一下:

;with tableA (LOCATION, PRODUCTS,   QTY)
as
(
select 'WH 1','PRODUCT NO. 1',10
union all
select  'WH 1','PRODUCT NO. 2',100
union all
select  'WH 1','PRODUCT NO. 333',5
union all
select  'WH 2','PRODUCT NO. YYY',22
)
, tableB (LOCATION, PRODUCTS,   QTY)
as
(
select 'WH 1','PRODUCT NO. 1',10
union all
select 'WH 1','PRODUCT NO. 2',100
union all
select 'WH 1','PRODUCT NO. 333',5
union all
select 'WH 1','PRODUCT NO. XXX',77
union all
select 'WH 2','PRODUCT NO. YYY',45
union all
select 'WH 1','PRODUCT NO. YYY',555
union all
select 'WH 2','PRODUCT NO. 1',14
)

select
    LOCATION
,   PRODUCTS
,   isnull(QtyA,0) [Qty A]
,   isnull(QtyB,0) [Qty B]
from
(
select
    LOCATION
,   PRODUCTS
,   QTY
,   'QtyA'  ColumnQty
from    tableA
union all
select
    LOCATION
,   PRODUCTS
,   QTY
,   'QtyB'  ColumnQty
from    tableB
) source
pivot
(
sum(QTY) for ColumnQty in ([QtyA],[QtyB])
) pvt

我已经对其进行了测试,可以看到它here.