简体   繁体   中英

MySQL Combine The Records From A Union Query

Can any one please assist. I have 2 tables, items issued to an employee and items returned from an employee. I have written the following union query and as would be expected I get 2 rows per result

select count(itemcode) as issued, 0 as returned, issue.employee, issue.itemcode 
from issue 
group by itemcode, employee
Union
select 0 as issued, count(itemcode) as returned, return.employee, return.itemcode 
from return 
group by itemcode, employee

The result is:

issued          returned       employee           itemcode
1               0              12345              abcd
0               1              12345              abcd
2               0              00001              abcd
0               3              00002              abcd

What can I do to combine the 2 records, keeping in mind that there are not always corresponding issued and returned records. The result I requiure is:

issued          returned       employee           itemcode
1               1              12345              abcd
2               0              00001              abcd
0               3              00002              abcd

Any help would be appreciated.

Thanks Steve

SELECT SUM(issued) issued,
       SUM(returned) returned,
       employee,
       itemcode
FROM ( select count(itemcode) as issued, 0 as returned, issue.employee, issue.itemcode 
       from issue 
       group by itemcode, employee
     Union
       select 0 as issued, count(itemcode) as returned, return.employee, return.itemcode 
       from return 
       group by itemcode, employee
     ) xxx
GROUP BY itemcode, employee

?

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