2016-08-08 45 views
-2

我有兩個表如下圖所示:比較Oracle數據庫中的兩個表

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 

我有這樣的代碼(我寫請求而不是按順序):

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_1和Table_2的區別。

我只有該代碼,我的表看起來像Table_1和Table_2。 當我編寫代碼時,我在Table_1和Table_2中看到了訂單。

但我想看到他們之間的差異。

+1

有沒有必要爲支點在這裏。 Google:'SQL-Server組concat' – sagi

+0

'order'是Oracle中的一個保留字,不能用作列名(除非用雙引號將它包圍)。您發佈的查詢實際上根本無法工作。 – sstan

回答

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.