select visit.rightcode AS 'รหัสบัตร',rightname AS 'สิทธิบัตร',
    count(distinct visit.pcucode,visit.pid) as 'คน' ,
    count(visitdrug.unit) as 'ครั้ง',
    visitdrug.costprice as 'ราคาทุน',
      visitdrug.realprice as 'ราคาขาย',
    sum(visitdrug.unit)as 'จำนวนยาที่จ่ายไป',
    sum(visitdrug.unit *visitdrug.costprice) as 'ยอดต้นทุนรวม',
    sum(visitdrug.unit *visitdrug.realprice) as 'ยอดขายรวม'
 
from visit 
left join visitdrug on visit.visitno = visitdrug.visitno and visit.pcucode = visitdrug.pcucode
left join cdrug on visitdrug.drugcode = cdrug.drugcode
LEFT JOIN cright ON visit.rightcode=cright.rightcode
where visitdate BETWEEN '2015-06-01' AND '2015-06-30'
group by visit.rightcode
ORDER BY visit.rightcode;
