sql—postgresql中的剩余库存计算

drkbr07n  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(297)

我试图减去产品内部的数量,将产品添加到发票中。为了弄清楚有多少产品有现货。

SELECT
    w_prod.prod_article_pvt_uuid
    ,sum(coalesce(w_prod.quantity, 0) - coalesce(s_item.quantity, 0)) as available
  FROM products w_prod
  LEFT JOIN items s_item ON s_item.whse_prod_pvt_uuid = w_prod.whse_prod_pvt_uuid
  LEFT JOIN documents s_doc ON s_item.sale_doc_pvt_uuid = s_doc.sale_doc_pvt_uuid
  GROUP BY w_prod.prod_article_pvt_uuid

预期产出如下:

+--------------------------------------+-----------+
| prod_article_pvt_uuid                | available |
+--------------------------------------+-----------+
| 470fda1a-54ab-11ea-a21d-de2e50192004 | 5         |
| 9a59a5ba-5ad8-11ea-a21d-de2e50192004 | 10        |
| c2c98260-5482-11ea-a21d-de2e50192004 | 9         |
+--------------------------------------+-----------+

但是上面的查询在 c2c98260-5482-11ea-a21d-de2e50192004 返回 21 相反。
看看sqlfiddle:http://sqlfiddle.com/#!2009年9月17日
你知道我做错了什么吗?怎么解决?
table:

create table products
(
    whse_prod_pvt_uuid uuid default uuid_generate_v1() not null
            primary key,
    t timestamp with time zone default CURRENT_TIMESTAMP(6),
    prod_article_pvt_uuid uuid not null,
    quantity numeric(16,6) default 1
);

create table documents
(
    sale_doc_pvt_uuid uuid default uuid_generate_v1() not null
            primary key,
    t timestamp with time zone default CURRENT_TIMESTAMP(6)
);

create table items
(
    sale_item_pvt_uuid uuid default uuid_generate_v1() not null
            primary key,
    t timestamp with time zone default CURRENT_TIMESTAMP(6),
    sale_doc_pvt_uuid uuid not null,
    whse_prod_pvt_uuid uuid not null,
    quantity numeric(16,6) not null
);
z8dt9xmd

z8dt9xmd1#

像这样解决:

SELECT
    w_prod.prod_article_pvt_uuid
    ,(sum(w_prod.quantity) - s.quantity) as available
FROM warehousing.products w_prod
LEFT JOIN (
    SELECT
        w_prod.prod_article_pvt_uuid
        ,sum(s_item.quantity) as quantity
    FROM warehousing.products w_prod
    LEFT JOIN sales.items s_item ON s_item.whse_prod_pvt_uuid = w_prod.whse_prod_pvt_uuid
    LEFT JOIN sales.documents s_doc ON s_item.sale_doc_pvt_uuid = s_doc.sale_doc_pvt_uuid    
    GROUP BY w_prod.prod_article_pvt_uuid
    ) s ON s.prod_article_pvt_uuid = w_prod.prod_article_pvt_uuid
GROUP BY w_prod.prod_article_pvt_uuid, s.quantity

它将在一个具体化的观点。如果有任何人有任何优化建议,请随时评论或张贴一个答案。

相关问题