Mysql
 sql >> Database >  >> RDS >> Mysql

mysql recupera tutte le righe utilizzando anche i riepiloghi

Unisci la tabella 1 alla tua query aggregata come sottoquery.

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