nodejsdeveloperskh

Calculate the inventory in kardex table

Mar 31st, 2021 (edited)
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. create table product(productId serial primary key);
  2. create table kardex(
  3.   id serial,
  4.   pId int,
  5.   in_inventory int,
  6.   out_inventory int,
  7.   createdAt timestamp default now(),
  8.   primary key(pid, id),
  9.   constraint fk_product
  10.     foreign key(pId)
  11.       references product(productId)
  12. );
  13.  
  14. # insert dummy data
  15. insert into product values (12);
  16. insert into product values (13);
  17. insert into kardex values(default, 12, 12, 0);
  18. insert into kardex values(default, 12, 0, 6);
  19. insert into kardex values(default, 13, 10, 0);
  20. insert into kardex values(default, 13, 0, 3);
  21.  
  22. # the previous query. This query does not work correctly. because it just uses the previous row not the whole previous records.
  23. with cte as (
  24.   select *, in_inventory - out_inventory as inventory
  25.   from kardex
  26.   where pId = 12
  27. ) select
  28.   id,
  29.   pId,
  30.   in_inventory,
  31.   out_inventory,
  32.   lag(inventory, 1) over (order by createdAt) as prev_inventory,
  33.   lag(inventory, 1) over (order by createdAt) - out_inventory as inventory
  34. from cte;
  35.  
  36. # this query fetch the final inventory
  37. select pId, sum(in_inventory - out_inventory) from kardex where pId = 12 group by pId;
  38.  
  39. # the correct query. these queries had the same result
  40. select *, sum(in_inventory - out_inventory) over (order by createdAt) as inventory from kardex where pId = 12 order by createdAt;
  41. select *, SUM(in_inventory - out_inventory) over (order by id) as inventory from kardex where pId = 12;
Add Comment
Please, Sign In to add comment