MySQL如何获取项目总和

时间:2017-07-14 11:03:13

标签: mysql sql

我在编写正确的查询以解决我的问题时遇到了很大的问题。如此快速地描述我的问题:

A是由产品B和C组成的集合。例如,集合A由4xB和1xC制成.le集合A由4xB和1xC制成。

Set A
4x B
1x C

我也可以单独销售产品B或C.

因此,如果我卖出一套A和一件B,我应该得到像

这样的结果
Product:   Sold:
A          1
B          5
C          1 

数据结构:

table products
id  name
1   A
2   B
3   C

table products_subset
id    parent_id    product_id    amount
1     1            2             4
2     1            3             1

table documents
doc_id   type    code
1        bill    INV-1
2        bill    INV-2

table document_products
id   doc_id   prod_id   amount    price
1    1        1         1         10
2    2        2         1         2

如果查询无法解决这个问题,那么我只需要编写一个代码来进行数学运算,但我希望在查询本身尽可能多地做。

2 个答案:

答案 0 :(得分:2)

SELECT 
    product_id, `name`, SUM(amount)
FROM
    (SELECT 
        dp.product_id, p.`name`, dp.amount
    FROM
        document_products dp
    JOIN products p ON p.id = dp.product_id 
    UNION ALL 
    SELECT 
        ps.product_id, p1.`name`, ps.amount
    FROM
        document_products dp
    JOIN products p ON p.id = dp.product_id
    JOIN products_subset ps ON dp.product_id = ps.parent_id
    JOIN products p1 ON p1.id = ps.product_id) AS t1
GROUP BY 1 , 2

结果

id  name    amount
1   A       1
2   B       5
3   C       1

答案 1 :(得分:0)

我设法将返回正确金额的查询放在一起。我的整个问题:

select warehouse_id, sum(amount_reserved), sum(amount_shipped) from (
select
    doc.warehouse_id warehouse_id,
    sum(puso.so_amount) amount_reserved,
    sum(puso.so_amount_shipped) amount_shipped
from
    products_use pu
    left join products_use_documents puso on (puso.company_id = 1111 and 
puso.products_use_id = pu.id)
    left join documents doc on (doc.id = puso.parent_id and doc.company_id = 1111)
where
    pu.company_id = 1111
    and pu.a_id = 11112222333
    and pu.parent_type = 'PR_SO'
    and doc.status_closed_manually = 0
    and doc.status_shipped = 0
    and doc.warehouse_id is not null
    and IF(puso.so_amount is not null, puso.so_amount, 0) > IF(puso.so_amount_shipped is not null, puso.so_amount_shipped, 0)
UNION
select
    doc.warehouse_id warehouse_id,
    sum(puso.so_amount * ps.amount) amount_reserved,
    sum(puso.so_amount_shipped * ps.amount) amount_shipped
from
    product_sets ps
    left join products_use pu on (ps.product_id = pu.a_id)
    left join products_use_documents puso on (puso.company_id = 1111 and puso.products_use_id = au.id)
    left join documents doc on (doc.id = puso.parent_id and doc.company_id = 1111)
where
    ps.company_id = 1111 and
    ps.product_set_id = 11112222333 and
    pu.company_id = 1111
    and pu.parent_type = 'PR_SO'
    and doc.status_closed_manually = 0
    and doc.status_shipped = 0
    and doc.warehouse_id is not null
    and IF(puso.so_amount is not null, puso.so_amount, 0) > IF(puso.so_amount_shipped is not null, puso.so_amount_shipped, 0)) l
group by l.warehouse_id