Sql 如何实现布尔或更新指令?

Sql 如何实现布尔或更新指令?,sql,postgresql,Sql,Postgresql,我正在使用postgresql。。。 我需要执行一个函数,合并表中的两行 假设我已经有了这两行的id,可以合并它们 示例: id quantity isOK 5 20 FALSE 5 10 FALSE 6 30 TRUE 6 35 FALSE 调用id 5后,表将更改为: id quantity isOK 5 30 FALSE 6 30 TRUE 6 35 FALSE 如果再次调用

我正在使用postgresql。。。 我需要执行一个函数,合并表中的两行

假设我已经有了这两行的id,可以合并它们

示例:

id quantity isOK
5     20     FALSE
5     10     FALSE
6     30     TRUE
6     35     FALSE
调用id 5后,表将更改为:

id quantity isOK
5     30     FALSE
6     30     TRUE
6     35     FALSE
如果再次调用id 6上的表将更改为:

id quantity isOK
5     30     FALSE
6     65     TRUE
因此,基本上每个调用取两行,并从中组合出一行

到目前为止,我只需将1号的数量添加到2号,然后删除1号

我需要修改我的函数,以便在
isOK
字段上有
BOOLEAN或
操作。
如果
,有没有办法不用
?
这就是我如何使用
IF

CREATE OR REPLACE FUNCTION func()
  RETURNS integer AS

   ......

    select isOK into x from A where firstrecord

    if x then
        update A set isOK=x where secondrecord
    end if;

   update quantity

   delete the first record

return 0;                       
end;                
$BODY$
  LANGUAGE plpgsql VOLATILE

首先将所需id作为参数:

create function myfunc(selectedid integer) returns integer as
声明两个局部变量:

declare mergedquantity integer; mergedisOK boolean;
然后合并记录:

select sum(quantity), case when sum(isOK) > 0 then true else false end
into mergedquantity, mergedisOK
from a
where id = selectedid;
现在,您可以删除旧记录并插入合并记录:

delete from a where id = selectedid;
insert into a values(selectedid, mergedquantity, mergedisOK);

您可以使用case函数和sum

create table t_test1(id number,value number, fld Varchar2(10));
Insert into T_TEST1
   (ID, VALUE, FLD)
Values
   (1, 23, 'TRUE');
Insert into T_TEST1
   (ID, VALUE, FLD)
Values
   (1, 22, 'FALSE');
Insert into T_TEST1
   (ID, VALUE, FLD)
Values
   (2, 2, 'FALSE');
Insert into T_TEST1
   (ID, VALUE, FLD)
Values
   (2, 23, 'FALSE');



select id,sum(value),case(case sum(case fld
            when 'FALSE' then 0
            else 1
            end
)
        when 0 then 0
        else 1 
       end)
       when 1 then 'TRUE'
       else 'FALSE'
       end
      from t_test1
group by id;
EXISTS()

=-- The table
CREATE TABLE t_test(id INTEGER,value INTEGER, fld Boolean);
-- The data
INSERT INTO t_test (id, value, fld)
VALUES (1, 23, 'TRUE'), (1, 22, 'FALSE'), (2, 2, 'FALSE'), (2, 23, 'FALSE');

-- The query
SELECT t.id
        , SUM(t.value)
        , EXISTS( SELECT 1
        FROM t_test x
        WHERE x.id  = t.id AND x.fld = True
        ) AS fld
FROM t_test t
GROUP by t.id
        ;

另一种方法是来回转换为整数(布尔是无序的,所以不能对它们使用max)


为什么在这种(
调用id 5后,表将是:
)条件下有两行
id=6
。。看见edit@jarlh“分组帮助”在这里有什么作用?我不明白你的意思。@java你能显示你最终的预期输出吗?使用case和使用IF是一样的。。。。我想知道如果没有他们的话是不是也可以。
SELECT t.id
        , sum(t.value) AS value
        , MAX( t.fld::integer )::boolean AS fld
FROM t_test t
GROUP by t.id
        ;