2017-07-14 3 views
1

produced TableMySQL Summe der Spalten aus zwei Tabellen erhalten, die Menge mehrere Datensätze von demselben Produkt

order_items table

Meine Forderung ist zu bekommen Summe der produzierten Artikel Menge und verkauften Artikel. Meine Frage ist

select productions.created_at, 
     produced.expiry_date, 
     items.id as item_id, 
     items.quantity as 
     sold_quantity, 
     items.product_price as sailing_price, 
     sum(produced.quantity) as total_produced, 
     sum(items.quantity) as total_sold 
from productions inner join produced_products as produced 
on produced.production_id = productions.id 
inner join store_order_items as items 
on items.product_keeping_id = produced.keeping_id 
group by produced.keeping_id, items.product_keeping_id 

Diese Abfrage liefert

[0] => Array ( [created_at] => 2017-07-13 10:25:52 [expiry_date] => 2017-07-31 [item_id] => 2 [sold_quantity] => 1.00 [sailing_price] => 120 [total_produced] => 6.000 [total_sold] => 2.00 )

[1] => Array ( [created_at] => 2017-07-07 13:30:25 [expiry_date] => 0000-00-00 [item_id] => 3 [sold_quantity] => 1.00 [sailing_price] => 120 [total_produced] => 16.000 [total_sold] => 4.00 )

Diese Aufzeichnungen sind falsch. Es sollte

[0] (
     [total_sold] => 1 
     ), 
    [1] (
     [total_sold] => 1 
    ) 

zurückkehrt Wie kann ich richtiges Ergebnis

+0

erhalten werden Sie insgesamt verkauft Wert wrt zweite Tabelle Berechnung nur (Punkt) oder Sie müssen den Summenwert mit Kombinieren mit Produkttabelle? –

+0

Ich brauche separate Summe der Menge aus beiden Tabellen als total_produced und total_sold – Yasir

Antwort

2

Versuchen Sie diesen

select productions.created_at, 
produced.expiry_date, 
items.id as item_id, 
items.quantity as sold_quantity, 
items.product_price as sailing_price, 
sum(produced.quantity) as total_produced, 
(SELECT sum(t1.quantity) FROM `store_order_items` as t1 where t1.product_keeping_id = produced.keeping_id) as total_sold 
from productions inner join produced_products as produced 
on produced.production_id = productions.id 
inner join store_order_items as items 
on items.product_keeping_id = produced.keeping_id 
group by produced.keeping_id, items.product_keeping_id 
+0

@Yasir sind Sie diese Abfrage versucht? –

+0

ja, es hat funktioniert. Vielen Dank. – Yasir

+0

Gern geschehen :) –

Verwandte Themen