SQL查询两个表之间的差异

时间:2013-09-06 06:30:16

标签: sql db2

我有两个表:Bucket1Bucket2

两个表中的列都是:ToyIdPrice

Bucket1
-----------------------------
ToyId        |    Price
-----------------------------
A            |    10
B            |    20
C            |    30
D            |    40
E            |    50
-----------------------------

Bucket2
-----------------------------
ToyId        |    Price
-----------------------------
D            |    45
E            |    50
F            |    60
G            |    70
H            |    80
-----------------------------

我想要一个结果表如下:

Result
-----------------------------------------------------------
ToyId        |    PriceTab1    |    PriceTab2   |   Diff
-----------------------------------------------------------
A            |    10           |    NA          |    NA
B            |    20           |    NA          |    NA
C            |    30           |    NA          |    NA
D            |    40           |    45          |    5
E            |    50           |    50          |    0
F            |    NA           |    80          |    NA
G            |    NA           |    90          |    NA
H            |    NA           |    100         |    NA
-----------------------------------------------------------

上表包含: 1)普通玩具(D,E)

2)玩具在Bucket1但不在Bucket2(A,B,C)

3)Bucket2中的玩具但Bucket3(F,G,H)中没有玩具

4)价格差异(D,E)

是否可以在单个查询中实现此目的?

感谢阅读!

2 个答案:

答案 0 :(得分:3)

create table b1 (
  t_id varchar(1),
  price int
  );

  create table b2 (
  t_id varchar(1),
  price int
  );

 insert into b1 (t_id, price)
             values
             ('a', 10),('b', 20),('c', 30),('d', 40),('e', 50);
insert into b2 (t_id, price)
             values
             ('d', 45),('e', 50),('f', 60),('g', 70),('h', 80);  

选择

select t_id, sum(price1), sum(price2) 
from 
  (select t_id, price as price1, null as price2 from b1
   union all 
   select t_id, null as price1, price as price2 from b2) res
group by t_id;

将差异计算排除在范围之外

http://sqlfiddle.com/#!2/c669fc/6

答案 1 :(得分:2)

这是FULL JOIN的典型示例:

SELECT
    COALESCE(b1.ToyId, b2.ToyId)  AS ToyId,
    b1.Price                      AS PriceTab1,
    b2.Price                      AS PriceTab2,
    (b2.Price-b1.Price)           AS Diff
FROM
    Bucket1 AS b1
  FULL JOIN
    Bucket2 AS b2
      ON b1.ToyId = b2.ToyId ;