合并多个关联的行

时间:2016-10-27 15:30:44

标签: postgresql

我有一个表Trackings(visitor_id, field, value, type),用于记录动态/用户定义的字段

我想合并visitor Avisitor B,以便A中的每次跟踪都覆盖B。换句话说,覆盖B中与A中对应的所有跟踪(他们不需要在合并时指定所有相同的字段)

示例:

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与B合并应该产生

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

理想情况下,这应该是非常高效的

有什么想法吗?

1 个答案:

答案 0 :(得分: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