查询1:
SELECT sum(quantity)
FROM `tbl_stock`
WHERE item_id = '4'
AND div_id = '1'
AND internal_reel_no = 'DP1000585'
AND txn_type IN ('IN')
GROUP BY div_id, item_id, txn_type
QUERY2:
SELECT sum(quantity)
FROM `tbl_stock`
WHERE item_id = '4'
AND div_id = '1'
AND internal_reel_no = 'DP1000585'
AND txn_type IN ('IS')
GROUP BY div_id, item_id, txn_type
我想将Query1的sum(quantity)
减去Query2的sum(quantity)
。
请让我知道答案
答案 0 :(得分:2)
这是另一个选项,它更通用,不涉及任何原始查询逻辑:
SELECT sum(quantity) INTO @sum1
FROM `tbl_stock`
WHERE item_id = '4'
AND div_id = '1'
AND internal_reel_no = 'DP1000585'
AND txn_type IN ('IN')
GROUP BY div_id, item_id, txn_type;
SELECT sum(quantity) INTO @sum2
FROM `tbl_stock`
WHERE item_id = '4'
AND div_id = '1'
AND internal_reel_no = 'DP1000585'
AND txn_type IN ('IS')
GROUP BY div_id, item_id, txn_type;
SELECT @sum1- @sum2;
答案 1 :(得分:1)
的子查询。
select q1_sum-q2_sum
from( SELECT sum(quantity) as q1_sum
FROM `tbl_stock`
WHERE item_id = '4'
AND div_id = '1'
AND internal_reel_no = 'DP1000585'
AND txn_type IN ('IN')
GROUP BY div_id, item_id, txn_type
cross join
SELECT sum(quantity) as q2_sum
FROM `tbl_stock`
WHERE item_id = '4'
AND div_id = '1'
AND internal_reel_no = 'DP1000585'
AND txn_type IN ('IN')
GROUP BY div_id, item_id, txn_type
)
答案 2 :(得分:1)
我会尝试:
SELECT
sum(case when txn_type = 'IN' then quantity else 0 end)
- sum(case when txn_type = 'IS' then quantity else 0 end)
FROM `tbl_stock`
WHERE item_id = '4'
AND div_id = '1'
AND internal_reel_no = 'DP1000585'
AND txn_type IN ('IN','IS')
GROUP BY div_id, item_id
注意:这可以在MSSQL中运行 - 您必须在MySQL中尝试
答案 3 :(得分:1)
SELECT SUM( CASE WHEN txn_type = 'IN' THEN quantity
WHEN txn_type = 'IS' THEN -quantity
END
) AS result
FROM
( SELECT txn_type, SUM(quantity) AS quantity
FROM tbl_stock
WHERE item_id = '4'
AND div_id = '1'
AND internal_reel_no = 'DP1000585'
AND txn_type IN ('IN', 'IS')
GROUP BY div_id, item_id, txn_type
) AS grp
答案 4 :(得分:0)
SELECT sum(quantity)
FROM tbl_stock
WHERE item_id='4'
AND div_id='1'
AND internal_reel_no='DP1000585'
AND txn_type IN ('IS') OR txn_type IN ('IN')
GROUP BY div_id, item_id, txn_type