PL / pgSQL逐字段求和两个json或两行

时间:2019-03-07 16:34:09

标签: sql postgresql plpgsql

我试图花几个小时来找到问题的答案,但我没有:

我想将某些行(它们具有相同的日期和“名称”值)的所有值求和到另一个将成为“聚合值”的值。

为此,我选择所需的行,按日期/名称对所有行进行循环,然后对行字段进行最后一个循环,以将字段一一求和:

DO $code$

DECLARE 
date_trunc_by_hour record; 
row_for_hour record;
field_of_row_for_hour record;
aggreged metrics.bot%ROWTYPE;
first boolean := true;
BEGIN

--boucle par heure, loop by hour
FOR date_trunc_by_hour IN
SELECT date_trunc('hour',date) as date_trunc
FROM metrics.bot 
where aggrege = false 
group by date_trunc
LOOP
 RAISE INFO 'Recherche pour la date : %', date_trunc_by_hour.date_trunc;
--boucle par row dans l'heure, loop on each row for the hour selected
first := true ;
FOR row_for_hour IN
  SELECT *
    FROM metrics.bot 
    where date_trunc('hour',date) = date_trunc_by_hour.date_trunc       

    LOOP
    IF first = true 
        THEN
        aggreged := row_for_hour; -- if it's the first row, i take the values of this row to add ones of the others rows after
        RAISE INFO '%', aggreged;
        first = false;
        ELSE -- if its not the first, i want to add values field by field to the first one
            FOR field_of_row_for_hour IN select * from json_each(row_to_json(row_for_hour))
            LOOP

        -- Here i would like for each field of each row in the loop, to add incoming row value to aggreged value, value can be a json                                                                

            END LOOP;

    END IF;
    END LOOP;

END LOOP;

END $code$;

例如,前两行具有相同的bot / date对,应给出第三行:

 ===== ===================== ========= ========= ===== ============================ ========== 
  BOT          DATE           PROCESS   INSERT    MAJ             ERRORS             aggreged  
 ===== ===================== ========= ========= ===== ============================ ========== 
    1   2019-02-12 17:00:00   scan            2     5   {"société":1}                false     
    1   2019-02-12 17:00:00   scan            4     7   {"société":1,"enchere":1}    false     
    1   2019-02-12 17:00:00   scan            6    12   {"enchere":1, "société":2}   true      
 ===== ===================== ========= ========= ===== ============================ ========== 

我将在插入表之前删除第1行和第2行。

在我的记忆中,我用json强制转换解决了这个问题,但是我不记得如何。

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

您需要一个自定义聚合,该聚合对整数属性进行求和:

create or replace function jsonb_sum_attributes(jsonb, jsonb)
returns jsonb language sql as $$
    select jsonb_object_agg(key, sum)
    from (  
        select key, sum(value::int)
        from (
            select *
            from jsonb_each_text($1)
            union all
            select *
            from jsonb_each_text($2)
            ) s
        group by key
        ) s
$$;

create aggregate jsonb_sum_attributes_agg(jsonb) 
(  
    sfunc = 'jsonb_sum_attributes',
    stype = jsonb,
    initcond = '{}'
);

查询:

select bot, date, process, insert, maj, errors, aggreged
from bot
union 
select bot, date, process, sum(insert), sum(maj), jsonb_sum_attributes_agg(errors), true
from bot
group by bot, date, process
order by bot, date, process, aggreged

 bot |        date         | process | insert | maj |            errors            | aggreged 
-----+---------------------+---------+--------+-----+------------------------------+----------
   1 | 2019-02-12 17:00:00 | scan    |      2 |   5 | {"société": 1}               | f
   1 | 2019-02-12 17:00:00 | scan    |      4 |   7 | {"enchere": 1, "société": 1} | f
   1 | 2019-02-12 17:00:00 | scan    |      6 |  12 | {"enchere": 1, "société": 2} | t
(3 rows)    

Working example in rextester.