Reputation: 1391
<?php
$inventory_in = $db->get_one("SELECT COALESCE(SUM(Qty), 0)
FROM inventory Where id=12 AND inv_type = 'in' LIMIT 1");
$inventory_out = $db->get_one("SELECT COALESCE(SUM(Qty), 0)
FROM inventory Where id=12 AND inv_type = 'out' LIMIT 1");
$inventory = $inventory_in - $inventory_out;
?>
Possible to combine two queries into one?
Thank you.
Upvotes: 0
Views: 1869
Reputation: 360572
SELECT inv_type, COALESCE(SUM(Qty), 0)
FROM inventory
WHERE id=12 AND inv_type IN ('in', 'out')
GROUP BY inv_type
Upvotes: 0
Reputation: 5894
How about a conditional sum?
SELECT
SUM(CASE WHEN inv_type = 'in' THEN 1 ELSE 0 END) InSum
SUM(CASE WHEN inv_type = 'out' THEN 1 ELSE 0 END) OutSum
WHERE
id = 12
Or if you just want the result
SELECT
SUM(CASE inv_type WHEN 'in' THEN 1 WHEN 'out' THEN -1 ELSE 0 END) TotalSum
WHERE
id = 12
Upvotes: 0
Reputation: 52645
Assuming you want both values output you can use SUM/CASE
SELECT
COALESCE(SUM(CASE WHEN inv_type = 'in' THEN Qty ELSE 0 END ), 0) as Sum1,
COALESCE(SUM(CASE WHEN inv_type = 'out' THEN Qty ELSE 0 END ), 0) as Sum2
FROM inventory
WHERE id=12
LIMIT 1
You may want to add and inv_type in ('in', 'out')
to your where clause but its not required.
Upvotes: 2