PostgreSQL:合并两个表中的记录并计算平均值

时间:2018-07-17 07:19:35

标签: sql postgresql join

我有两个表table_1和table_2。 我想将table_1(具有特定ID)中的某些记录与table_2(具有特定ID)中的一些记录合并。

例如: 我想将ID为“ AA”的表_1中的所有记录与ID为“ HH”的表_2中的记录合并。但是ID“ HH”不应更改,但应通过计算平均值合并值列Val1和Val2。此外,仅应合并来自“ AA”和“ HH”的那些记录,这些记录共享相同的时间戳。 因此执行查询后,table_2看起来像这样。

这里是例子:

Table_1:
ID |     Timestamp    | Val1 | Val2
-----------------------------------
AA | 2018-14-07 00:00 | 203  | 294
BB | 2018-14-07 00:00 | 193  | 194
CC | 2018-14-07 00:00 | 193  | 136
AA | 2018-14-07 00:15 | 194  | 198
BB | 2018-14-07 00:15 | 124  | 594
CC | 2018-14-07 00:15 | 105  | 110

Table_2:
ID |     Timestamp    | Val1 | Val2
-----------------------------------
HH | 2018-14-07 00:00 | 123  | 311  
GG | 2018-14-07 00:00 | 156  | 202 
HH | 2018-14-07 00:15 | 200  | 502  
HH | 2018-14-07 00:30 | 303  | 198 
PP | 2018-14-07 00:00 | 111  | 123 

Table_2 (after executing the query):
ID |     Timestamp    | Val1 | Val2
-----------------------------------
HH | 2018-14-07 00:00 | 163  | 302  // Val1: (123 + 203)/2 = 163; Val2: (311+294)/2 = 302
GG | 2018-14-07 00:00 | 156  | 202 
HH | 2018-14-07 00:15 | 197  | 350  // Val1: (200 + 194)/2 = 197; Val2: (502+198)/2 = 350
HH | 2018-14-07 00:30 | 303  | 198  // values stay the same because no record with the ID "AA" and the timestamp "2018-14-07 00:30" is available.
PP | 2018-14-07 00:00 | 111  | 123 

请,如果您有一些问题需要进一步了解,请随时发表评论。然后,我将编辑问题以更好地理解。

2 个答案:

答案 0 :(得分:1)

要查询所需信息,请尝试:

select T2.ID,
       T2.Timestamp, 
       (T1.Val1 + T2.Val1)/2 Val1,
       (T1.Val2 + T2.Val2)/2 Val2
from Table2 T2 left join (
    select case ID when 'AA' then 'HH' end ID,
           Timestamp,
           Val1,
           Val2
    from Table1
) T1 on T2.ID = T1.ID and T2.Timestamp = T1.Timestamp

要基于Table2更新Table1,请尝试:

update Table2 as T2 set Val1 = (coalesce(T1.Value1, Val1) + Val1)/2,
                        Val2 = (coalesce(T1.Value2, Val2) + Val2)/2
from (
    select case ID when 'AA' then 'HH' else ID end ID,
           Timestamp,
           Val1 AS Value1,
           Val2 AS Value2
    from Table1
) T1 where T2.ID = T1.ID and T2.Timestamp = T1.Timestamp

答案 1 :(得分:0)

尝试一下

Select t2.ID, t2.Timestam, 
       Case when t1.Val1 is null Then t2.Val1 ELSE (T1.Val1 + T2.Val1)/2 END Val1,
       Case when t1.Val2 is null Then t2.Val2 ELSE (T1.Val2 + T2.Val2)/2 END Val2 
from #tbl2 t2
left join #tbl1 t1
on t1.Timestam = t2.Timestam
and t1.ID = 'AA' and t2.ID = 'HH'