2

我有两张桌子: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)

是否可以在单个查询中实现这一点?

谢谢阅读!

4

2 回答 2

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

于 2013-09-06T06:46:45.473 回答
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 ;
于 2013-09-06T06:35:23.300 回答