Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- create table product(productId serial primary key);
- create table kardex(
- id serial,
- pId int,
- in_inventory int,
- out_inventory int,
- createdAt timestamp default now(),
- primary key(pid, id),
- constraint fk_product
- foreign key(pId)
- references product(productId)
- );
- # insert dummy data
- insert into product values (12);
- insert into product values (13);
- insert into kardex values(default, 12, 12, 0);
- insert into kardex values(default, 12, 0, 6);
- insert into kardex values(default, 13, 10, 0);
- insert into kardex values(default, 13, 0, 3);
- # the previous query. This query does not work correctly. because it just uses the previous row not the whole previous records.
- with cte as (
- select *, in_inventory - out_inventory as inventory
- from kardex
- where pId = 12
- ) select
- id,
- pId,
- in_inventory,
- out_inventory,
- lag(inventory, 1) over (order by createdAt) as prev_inventory,
- lag(inventory, 1) over (order by createdAt) - out_inventory as inventory
- from cte;
- # this query fetch the final inventory
- select pId, sum(in_inventory - out_inventory) from kardex where pId = 12 group by pId;
- # the correct query. these queries had the same result
- select *, sum(in_inventory - out_inventory) over (order by createdAt) as inventory from kardex where pId = 12 order by createdAt;
- 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