Postgresql中的光标和更新

时间:2016-09-16 16:33:22

标签: sql postgresql

我在postgresql中编写了一个函数,用于使用两个游标更新表,代码执行正常但没有错误,但没有做任何事情。

我有三张桌子

  1. 产品大师
  2. 销售数据表
  3. 目标表
  4. 因此,在下面的函数中,我从1获取产品密钥,然后在销售表中计算产品销售的商店/销售点数,然后相应地更新第三个表,

    我需要每周计算每种产品的出口数量。但它们应该是唯一的,例如,如果产品在第一周在商店A和B销售,则第一周的商店数量应为2,如果在下周出售B,C,D,则第二周的总数应为4如果它在第三周以A和D出售,那么第三周的总数应该是4。我该怎么做。

    任何帮助将不胜感激。

      create or replace function StCount() returns void as
       $BODY$
        Declare
          ik1 integer ; 
        wk1  integer ; 
        Cur1 CURSOR FOR SELECT  ik  From table1 ; 
          Cur2   CURSOR FOR SELECT distinct(wk) FROM table2 order by wk asc;
    
    
      begin
        OPEN Cur1 ;
       WHILE (Found) Loop 
       FETCH  next from Cur1 INTO ik1  ; 
    
    OPEN Cur2 ;
    
      WHILE (Found) Loop 
         FETCH  next from Cur2 INTO wk1;    
    
                    update table3 set skly =(select count(sk)from table2 a  
            where a.ik = ik1   and a.wk = wk1  
            and a.sk not in (select distinct (sk) from table2
            where ik = ik1 and wk <= wk1 - 1 ))
            where ik = ik1 and wk = w1
            ;
    
    
      End loop ;
    CLOSE Cur2;
    
      end loop ;
    
       CLOSE Cur1;
    
      END;
       $BODY$
       LANGUAGE plpgsql VOLATILE;
    

1 个答案:

答案 0 :(得分:0)

您没有告诉我们您的表格是什么样的,或者您正在处理的数据到底是什么,所以我在这里做了很多假设。

使用此设置:

create table product (id integer primary key);
create table sales (id serial primary key, product_id integer, store text, wk integer);

insert into product values (1),(2),(3),(4);

insert into sales (product_id, store, wk)
values
  (1, 'A', 1),
  (1, 'B', 1),
  (1, 'B', 2),
  (1, 'C', 2),
  (1, 'D', 2),
  (1, 'A', 3),
  (1, 'D', 3);

每件产品,商店和周的累计销售额可以这样计算:

select product_id, 
       store,
       wk,
       count(store) over (partition by product_id order by wk) as sofar
from (
  select product_id, 
         store, 
         wk,
         row_number() over (partition by product_id, store order by wk) as rn
  from sales
  order by product_id, store
) t
where rn = 1;

请注意,product表实际上并未在此中使用,但可以轻松地将其连接到内部查询。

对于上面的示例数据,返回:

product_id | store | wk | sofar
-----------+-------+----+------
         1 | A     |  1 |     2
         1 | B     |  1 |     2
         1 | C     |  2 |     4
         1 | D     |  2 |     4

现在,此结果可用于更新目标表:

update target_table
   set slky = t.sofar
from (
    select product_id, 
           store,
           wk,
           count(store) over (partition by product_id order by wk) as sofar
    from (
      select product_id, 
             store, 
             wk,
             row_number() over (partition by product_id, store order by wk) as rn
      from sales
      order by product_id, store
    ) t
    where rn = 1
) s
where s.wk = target_table.wk 
  and s.product_id = target_table.product_id
  and s.store = target_table.store;

这假设(product_id, store, wk)的{​​{1}}组合在target_table中是唯一的。由于您在示例中对表和列的名称进行了模糊处理,因此很难说。