mysql - How to distinct sum() when using joins -
i have 2 tables. 1 holds data ok parts , other rejects.
i receive data in following format:
| yyyy-mm | sum(ok.qty) | sum(reject.qty) | reject % |
1) possible use join
, kind of distinct sum(ok.qty)
?
select date_format(date, '%y-%m'), sum(ok.qty), sum(reject.qty), sum(reject.qty) / sum(reject.qty + ok.qty) reject_percent ok join reject on ok.id = reject.ok_id group date_format(date, '%y-%m')
2) if not how eliminate duplicate sub-queries?
select date_format(date, '%y-%m'), sum(ok.qty), (select qty reject ok_id = ok.id), (select qty reject ok_id = ok.id) / ( (select qty reject ok_id = ok.id) + sum(ok.qty) ) reject_percent ok group date_format(date, '%y-%m')
right had write 1 query 3 times.
database design:
ok.id
can have mutiple rejects.
you can try this..
select date_format(date, '%y-%m'), sum(ok.qty), sum(reject.qty), ((sum(reject.qty) / sum(reject.qty + ok.qty))*100)as reject_percent ok inner join (select ok_id,sum(qty) qty reject group ok_id) reject on ok.id = reject.ok_id group date_format(date, '%y-%m')
Comments
Post a Comment