I have two simple tables. tbl_purchased
and tbl_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
I need to take
I can do that using following queries separately.
SELECT col_item_name, SUM(col_no_of_items)
FROM tbl_purchased
GROUP BY col_item_name;
and
SELECT col_item_name, SUM(col_no_of_items)
FROM tbl_sold
GROUP BY col_item_name;
now I need to take the current stock.
That means, (SUM of purchased items - SUM of sold items) GROUP BY item name.
Can I do that using SINGLE sql query?
Try something like bellow (might need to adjust it though):
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;
Or you could use
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
This perfectly work for you
SELECT p. name
, ((SELECT SUM(NO) FROM purcahse
WHERE name
=p.name)-(SELECT COALESCE(SUM(NO),0) FROM sell
WHERE name
=s.name)) remaining FROM purcahse
p LEFT JOIN sell
s ON p.name=s.name GROUP BY p.name;
enjoy thanks :)
Suggestion: join your first table expression (need to give the summarization a name eg col_no_of_items_purchased
) to tbl_curent_stock
, then do simple arithmetic. You should also consider items that haven't been purchased by anti-joining. Then UNION
the two together:
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 );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.