MySQL Group By Product Id但不是具有序列号的产品

时间:2014-07-12 03:07:19

标签: php mysql sql

有人可以帮助我如何为此进行有效的mysql查询吗?

我需要进行查询以获取所有订购商品的总金额。

结合。

我需要进行查询以获取所有收到的项目的总和数量。

请注意某些产品在收到序列号时有些序列号在我的'received_po_details'表中。这就是我遇到问题的地方,因为序列号会使得收到的总和加倍。

表:received_po_details

i_rpoh_id   i_p_id  i_quantity_received s_product_serial
1           1       100 
1           2       100 
1           3       50  
1           4       25  
1           7       100 
1           8       50  
1           6       1                   XYZ1
1           6       1                   XYZ2
1           5       1                   ABC1
1           5       1                   ABC2

现在我需要将这两个独立的sql组合起来。 我不想在可能的情况下使用Union语句 ...

- 获取订购的总数量

SELECT
    products.i_id AS 'ID',
    products.s_name AS 'Name',
    COALESCE(SUM(purchase_order_details.i_quantity_ordered),0) AS 'Total Quantity Ordered'
FROM
    products
LEFT JOIN
    purchase_order_details
    ON
    products.i_id = purchase_order_details.i_p_id
GROUP BY
    products.i_id   

-- to get the Total Quantity Received
SELECT
    products.i_id AS 'ID',
    products.s_name AS 'Name',
    COALESCE(SUM(received_po_details.i_quantity_received),0) AS 'Total Quantity Received'
FROM
    products
LEFT JOIN
    received_po_details
    ON
    products.i_id = received_po_details.i_p_id
GROUP BY
    products.i_id

1 个答案:

答案 0 :(得分:0)

您可以通过创建派生表或每种类型的和来组合这些查询(在下面的查询中,它们被命名为t1t2)并将派生表连接到主要表产品表。

SELECT
    p.i_id AS 'ID',
    p.s_name AS 'Name',
    COALESCE(t1.total,0) 'Total Quantity Ordered',
    COALESCE(t2.total,0) 'Total Quantity Received'
FROM products p
LEFT JOIN (
    SELECT 
        pod.i_p_id,
        SUM(pod.i_quantity_ordered) total
    FROM purchase_order_details pod
    GROUP BY pod.i_p_id
) t1 ON t1.i_p_id = p.i_id
LEFT JOIN (
    SELECT 
        rpd.i_p_id,
        SUM(rpd.i_quantity_received) total
    FROM received_po_details rpd
    GROUP BY rpd.i_p_id
) t2 ON p.i_id = t2.i_p_id