如何取得列值之和的差异?

时间:2016-10-28 08:15:31

标签: php mysql sql database

我有两个简单的表格。 tbl_purchasedtbl_sold

tbl_purchased

col_item_name col_no_of_items
Fan                         5
Builb                       5
Oven                        5
Fan                         2
Builb                       2

tbl_sold

col_item_name col_no_of_items
Fan                         3
Oven                        1

我需要

  1. 购买商品的总和,GROUP BY商品名称。
  2. 已售商品的总和,GROUP BY商品名称。
  3. 我可以单独使用以下查询来做到这一点。

    SELECT col_item_name, SUM(col_no_of_items)
    FROM tbl_purchased
    GROUP BY col_item_name;
    

    SELECT col_item_name, SUM(col_no_of_items)
    FROM tbl_sold
    GROUP BY col_item_name;
    

    现在我需要拿走当前的股票。

    enter image description here

    这意味着, (已购买商品的总和 - 已售商品的总和)GROUP BY商品名称。

    我可以使用SINGLE sql查询吗?

4 个答案:

答案 0 :(得分:2)

尝试类似下面的东西(可能需要调整它):

SELECT p.col_item_name, SUM(p.col_no_of_items) - SUM (s.col_no_of_items)
FROM tbl_purchased p
left join tbl_sold s on p.col_item_name=s.col_item_name
GROUP BY p.col_item_name;

答案 1 :(得分:0)

或者你可以使用

SELECT col_item_name, SUM(no_purchased) - SUM(no_sold) AS item_stock
FROM
   (SELECT col_item_name, col_no_of_items AS no_purchased, 0 AS no_sold
    FROM tbl_purchased
    UNION ALL
    SELECT col_item_name, 0 AS no_purchased,col_no_of_items AS no_sold)
GROUP BY col_item_name

答案 2 :(得分:0)

这完全适合你

SELECT p。table1-|md5_col1|col2|.... table2-|same_md5_frm_table1|col2|col3|.... table3-|same_md5_frm_table1|col2|col3|.... table4-|same_md5_frm_table1|col2|col3|.... ,((SELECT SUM(NO)FROM name WHERE purcahse = p.name) - (SELECT COALESCE(SUM(NO),0)FROM { {1}} WHERE name = s.name))  剩余FROM sell p LEFT JOIN name s ON p.name = s.name GROUP BY p.name;

享受谢谢:)。

答案 3 :(得分:0)

建议:将您的第一个表格表达式(需要将摘要命名为col_no_of_items_purchased)加入tbl_curent_stock,然后执行简单的算术运算。您还应该考虑反加入未购买的商品。然后UNION两个在一起:

SELECT col_item_name,
       col_no_of_items - col_no_of_items_purchased AS col_no_of_items
FROM tbl_curent_stock
     NATURAL JOIN
     ( SELECT col_item_name,
              SUM(col_no_of_items) AS col_no_of_items_purchased
         FROM tbl_purchased
        GROUP
           BY col_item_name ) AS t
UNION
SELECT col_item_name, col_no_of_items
  FROM tbl_curent_stock
 WHERE col_item_name NOT IN ( SELECT col_item_name
                                FROM tbl_purchased );