Mysql
 sql >> Datenbank >  >> RDS >> Mysql

mysql ruft alle Zeilen ab und verwendet auch Zusammenfassungen

Verbinden Sie Tabelle 1 mit Ihrer aggregierten Abfrage als Unterabfrage.

SELECT t1.name, t1.apn, t1.bpn, t1.code, t2.*
FROM table_1 AS t1
JOIN (
    SELECT APN, count(APN) AS APN_count, min(aCost) AS min_aCost, min(bCost) AS min_bCost, ceil(avg(aQty)) AS avgQty, 
    max(aQty) AS maxQty, sum(bShipped) AS sum_bShipped, 
    CONCAT(truncate((avg(aResale)-avg(aCost))/avg(aResale),2) * 100,'%') AS avg_Margin FROM
    (SELECT name, APN, BPN, aCost, aQty, code
        FROM table_1
        WHERE customer = '12345' AND
        aDate >= '2013-01-01' and
        aDate <= '2015-12-12') as qh
    INNER JOIN (SELECT CPN, bCost, bResale, bShipped from table_2 
    WHERE customer = '12345') as ih
    ON qh.APN = ih.CPN
    WHERE bShipped > 0
    GROUP BY qh.APN) AS t2
ON t1.APN = t2.APN