简体   繁体   中英

MYSQL - combining multiple queries from same table

Trying to get:

trans_id  |  qty  |  ptotal
---------------------------
100       |   30  |   2
101       |   25  |   0

from inv table

trans_id  |  pull_from_trans  | trans_desc  | qty | itc_part_id
---------------------------------------------------------------
100       |   null            |   rec       |  30 |   1003
101       |   null            |   rec       |  25 |   1010
102       |   100             |   pull      |   1 |   1003
103       |   100             |   pull      |   1 |   1003         

using (but not working)

SELECT tb1.trans_id, tb1.qty,sum(tb2.qty) as ptotal
FROM inv tb1 where tb1.trans_desc='rec'
    INNER JOIN inv tb2 ON tb1.trans_id=tb2.pull_from_trans
WHERE tb2.trans_desc='pull' GROUP BY tb2.pull_from_trans

You have two where clauses there. Put the first validation as an AND on the final WHERE clause:

SELECT tb1.trans_id, tb1.qty, sum(tb2.qty) AS ptotal
FROM inv tb1
INNER JOIN inv tb2 ON tb1.trans_id = tb2.pull_from_trans
WHERE tb2.trans_desc = 'pull' AND tb1.trans_desc = 'rec'
GROUP BY tb2.pull_from_trans

Not very sure about your GROUP BY. I would probably do: GROUP BY tb1.trans_id, tb1.qty , if you are asking for tb1.qty , but see if that gives you what you want.

I am not sure what exactly you are trying to do, but the following query will give the output you need.

SELECT tb1.trans_id, tb1.qty, IFNULL(sum(tb2.qty),0)  AS ptotal
FROM inv tb1
LEFT JOIN inv tb2 ON tb1.trans_id = tb2.pull_from_trans
WHERE tb2.trans_desc = 'pull' OR tb1.trans_desc = 'rec'
GROUP BY tb1.trans_id

SQL Fiddle here.

http://www.sqlfiddle.com/#!2/2acb5a/7

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM