sql - MySQL: How do I SUM non duplicates values when doing multiples JOINS -
Text after "
I try to sum values from columns, a question that takes some of the workload
example:.
Select p.id product_id, SUM (out_details.out_details_quantity) stock_bought_last_month, SUM (order_details.order_quantity) as product as stock_already_commanded as P Interiors Out_details.product_id = p.id out_details Join Insider Order_details.product_id = order_details at p.id WHEER p.id = 9507 group out_details.out_details_pk, order_details.id;
I get this result:
+ ------------ + --------- - --------------- + ------------------------- + | Product_id | Stock_bust_lost_moth | Stock_already_commanded | + ------------ + ------------------------- + ---------- --------------- + | 9507 | 22 | 15 | | 9507 | 22 | 10 | | 9507 | 10 | 15 | | 9507 | 10 | 10 | | 9507 | 5 | 15 | | 9507 | 5 | 10 | + ------------ + ------------------------- + ---------- --------------- +
Now, I want to SUM values, but of course there are duplicates. I also have group of product_id For: stock_bought_last_month as SUM (out_details.out_details_quantity), as the product p_id in the form of p.id selection (order_details.order_quantity), as in the form of the product pi. Join stock_already_commanded out_details.product_id = p.id intermediate to join order_details.product_id = p.id ORDER_DETAILS where p.id by p.id = 9507 group;
Result:
+ ------------ + ------------- ------------ + ------------------------- + | Product_id | Stock_bust_lost_moth | Stock_already_commanded | + ------------ + ------------------------- + ---------- --------------- + | 9507 | 74 | 75. + ------------ + ------------------------- + ---------- --------------- +
The result was wanted:
+ ------- - ---- + ------------------------- + ------------------ - ------ + | Product_id | Stock_bust_lost_moth | Stock_already_commanded | + ------------ + ------------------------- + ---------- --------------- + | 9507 | 37 | 25 | + ------------ + ------------------------- + ---------- --------------- +
How can I ignore duplicates? Of course, the count of lines can change!
select
P.Id, be organized (DetailTotals altogether, 0) In stock_bought_last_month, Collage (OrderTotals Total, 0) Include the product P as the product as stock_already_commanded (Include O1.product_id, Yoga (O1.out_details_quantity) as the total O1 group as O1 group O1.product_id as details) include DetailTotals.product_id = as the Tetlus = P.id Left (selection O2.product_id, add (O2.order_quantity) as the total ORDER_DETAILS O2 group Based on O2.product_id form) as OrderTotals on OrderTotals.product_id = P.id where P.Id = 9507
Comments
Post a Comment