2016-10-27 107 views
0

我有一個表Trackings(visitor_id, field, value, type)它記錄動態/用戶自定義字段合併多個相關行

我要合併visitor Avisitor B,使得對於每一個在A跟蹤,將其覆蓋在B。換句話說,覆蓋所有的漏電痕跡在BA相應的(它們不需要具有所有在合併中指定的相同的字段)

實施例:

visitor_id field   value  type 
A   name   Jack  string 
A   orders   5   integer 
B   orders   2   integer 
B   age    30   integer 
B   signed_up_at 1/1/1990 date  

合併訪問者A與乙應該產生

visitor_id field   value   type 
B   orders   5    integer 
B   age    30    integer 
B   signed_up_at 1/1/1990  date  
B   name   Jack 

理想的,這應該是相當高性能

任何想法?

回答

0

你可以試試這個查詢看到部分結果

SELECT B.*, A.* 
FROM yourTable B 
FULL JOIN yourTable A 
    ON B.field = A.field 
AND B.visitor_id = 'B' 
AND A.visitor_id = 'A' 

SQL DEMO

SELECT 'B' as visitor_id, 
     COALESCE(A.field, B.field) as field, 
     COALESCE(A.value, B.value) as value, 
     COALESCE(A.type, B.type) as type 
FROM yourTable B 
FULL JOIN yourTable A 
    ON B.field = A.field 
AND B.visitor_id = 'B' 
AND A.visitor_id = 'A' 
WHERE B.visitor_id = 'B' 
    OR A.visitor_id = 'A' 

輸出

enter image description here

+0

這是高性能的嗎?另外,我正在尋找一個UPDATE查詢 – Tarlen