Select mc.med_idlab,mi.namelab,mu.name,mi.unitprice
,mc_ii.date_update
,mc_ii.remain AS num1,(mc_ii.remain*mi.unitprice) AS price1
,mro.med_amount As num2,(mro.med_amount*mi.unitprice) AS price2
,(mc_ii.remain+mro.med_amount) AS num3,(SUM(mc_ii.remain*mi.unitprice)+SUM(mro.med_amount*mi.unitprice)) AS price3
,aa.num4,(aa.num4*mi.unitprice) AS price4
,mr.remain AS num5, (mr.remain*mi.unitprice) AS price5
,mc_ii.med_remainall
From med_cal mc
Left outer join (
Select idlab, Sum(confirm) AS num4 from med_inorder group by idlab
) aa On mc.med_idlab = aa.idlab
LEFT JOIN (
SELECT *
FROM med_cal
WHERE date_update BETWEEN DATE_ADD('2017-04-01', INTERVAL -1 MONTH)
AND DATE_ADD('2017-04-30', INTERVAL -1 MONTH)
) mc_ii ON mc.med_idlab = mc_ii.med_idlab
INNER JOIN med_items mi ON mi.med_items_id = mc.med_idlab
INNER JOIN med_unit mu ON mu.med_unit_id = mi.idunit
INNER JOIN med_receive_order mro ON mro.med_idlab = mc.med_idlab
INNER JOIN med_remain mr ON mr.med_idlab = mc.med_idlab
where mc.date_update between '2017-04-01'AND '2017-04-30'
and mro.date_update IN (SELECT MAX(a.date_update) AS date_update FROM med_receive_order a GROUP BY a.med_idlab)//code ที่ SinKasin แนะนำครับ
group by mc.med_idlab
ORDER BY mi.med_items_id ASC
LEFT JOIN (
SELECT *
FROM med_cal
WHERE date_update BETWEEN DATE_ADD('2017-04-01', INTERVAL -1 MONTH)
AND DATE_ADD('2017-04-30', INTERVAL -1 MONTH)
) mc_ii ON mc.med_idlab = mc_ii.med_idl
LEFT JOIN (
SELECT *
FROM med_cal
WHERE date_update BETWEEN DATE_ADD('2017-04-01', INTERVAL -1 MONTH)
AND DATE_ADD('2017-04-30', INTERVAL -1 MONTH) and
date_update IN (SELECT MAX(a.date_update) AS date_update FROM med_receive_order a GROUP BY a.med_idlab)
) mc_ii ON mc.med_idlab = mc_ii.med_idlab
LEFT JOIN (
SELECT *
FROM med_cal
WHERE date_update BETWEEN DATE_ADD('2017-04-01', INTERVAL -1 MONTH)
AND DATE_ADD('2017-04-30', INTERVAL -1 MONTH) and
date_update IN (SELECT MAX(a.date_update) AS date_update FROM med_cal a GROUP BY a.med_idlab)
) mc_ii ON mc.med_idlab = mc_ii.med_idlab