比较Oracle数据库中的两个表

时间:2016-08-08 12:19:37

标签: database oracle pivot-table

我有两张如下表:

Table_1  

Customer    Order 
----------------------
David       Pizza
David       Cola
Jack        Milkshake
Michael     Pizza
Michael     Milkshake
Alan        Cola
Alan        Pizza

Table_2

Customer    Order
----------------------
David       Pizza
David       Cola
Jack        Milkshake
Michael     Pizza
Michael     Milkshake
Alan        Milkshake
Alan        Pizza

我有这样的代码(我写了Request而不是Order):

 WITH t AS
 (SELECT customer
    ,row_number() over(PARTITION BY customer ORDER BY "ORDER" DESC) order_no
     ,"ORDER"
     ,COUNT(*) over(PARTITION BY customer) order_cnt
  FROM   table_1)
  SELECT customer, order1, order2, order3, order_cnt "Counts of Orders"
  FROM   t
  pivot (MAX("ORDER") FOR order_no IN(1 AS order1, 2 AS order2,AS order3))
  ORDER  BY customer;

正在制作:

  Table_1

 Customer     order1     order2     order3  counts of orders
 -----------------------------------------------------------
 David        pizza      cola       null            2
 Jack        milkshake   null       null            1
 Michael      pizza    milkshake    null            2
 Alan         cola      pizza        null           2

我实现了代码Table_2,它正在实现:

Customer     Order1     Order2    Order3     Counts of Orders
-------------------------------------------------------------
 David       Pizza      Cola       null             2
 Jack        Milkshake  null       null             1
 Michael     Pizza      Milkshake  null             2
 Alan        Milkshake   Pizza      null            2

我想比较这些表格。例如:David在Table_1和Table_2中订购了披萨和可乐。这是真的。

但是Alan在Table_1中订购了可乐,披萨,在Table_2中订购了奶昔,披萨 我希望看到Table_1和Table_2之间存在差异。

我只有那些代码,我的表格看起来像Table_1和Table_2。 当我编写代码时,我在Table_1和Table_2中都看到了订单。

但我希望看到它们之间的差异。

1 个答案:

答案 0 :(得分:2)

这样的东西?

WITH t AS
 (SELECT customer
        ,row_number() over(PARTITION BY customer ORDER BY "ORDER" DESC) order_no
         ,"ORDER"
         ,COUNT(*) over(PARTITION BY customer) order_cnt
  FROM   table_1)
SELECT customer, order1, order2, order3, order_cnt "Counts of Orders"
FROM   t
pivot (MAX("ORDER") FOR order_no IN(1 AS order1, 2 AS order2, 3 AS order3))
ORDER  BY customer;

这是我的结果:

CUSTOME ORDER1    ORDER2    ORDER3    Counts of Orders
------- --------- --------- --------- ----------------
David   Pizza     Cola                               2
Jack    Milkshake                                    1
Michael Pizza     Milkshake                          2

3 rows selected.