I have a Bill table like this
BillNo - 1, ServiceCode -1, ServiceName - 'Lab test' , ItemAmount -30
BillNo -1, ServiceCode -2, ServiceName -'Consultation', ItemAmount -70
I need output like this
Bill No -1, Total Bill Amount-100 , Lab Test-30, Consultation-70, Drugs-0, Misc-0
So basically i need the Bill Amount which is the SUM of all ItemAmount Grouped by BillNo. Then in the same row i need to distribute this Bill Amount to the 4 ServiceNames. So 100 gets distributed as 30 for Lab test and 70 for Consultation.
This gave me what i want but it is not optimal.
SELECT
BD.BILLNO AS BN,
SUM(BD.ITEMAMOUNT) AS "Bill Amount",
(SELECT SUM(BD.ITEMAMOUNT) FROM BILLDETAILS BD
WHERE SERVICENAME LIKE '%Lab%'
AND BD.BILLNO = BN ) AS "Lab",
(SELECT SUM(BD.ITEMAMOUNT) FROM BILLDETAILS BD
WHERE SERVICENAME LIKE '%Consult%'
AND BD.BILLNO = BN ) AS "Consultation",
(SELECT SUM(BD.ITEMAMOUNT) FROM BILLDETAILS BD
WHERE SERVICENAME LIKE '%Procedure%'
AND BD.BILLNO = BN ) AS "Procedures",
(SELECT SUM(BD.ITEMAMOUNT) FROM BILLDETAILS BD
WHERE SERVICENAME LIKE '%Drugs%'
AND BD.BILLNO = BN ) AS "Drugs",
(SELECT SUM(BD.ITEMAMOUNT) FROM BILLDETAILS BD
WHERE SERVICENAME NOT LIKE '%Lab%'
AND SERVICENAME NOT LIKE 'Consult%'
AND SERVICENAME NOT LIKE '%Procedure%'
AND SERVICENAME NOT LIKE '%Drugs%'
AND BD.BILLNO = BN )AS "Miscellaneous"
FROM BILLDETAILS BD
GROUP BY BD.BILLNO
How can i improve this mySQL query ?
Thanks. Chak.