I have a database from a hospital. In a table there's 1 or more transaction numbers and almost all of them only contain 1 Doctor ID. The table hasn't been normalized yet.
The data looks like the following:
Trans_No |Doctor_ID |Trans_Type |PM |Cost
10.853329 | |ADMINISTRASI | |0.00
10.853329 |10004 |JASA MEDIS | |25000.00
10.853329 | |OBAT RESEP FARMASI NO : 1077 |F |2000.00
10.836033 | |ADMINISTRASI | |0.00
10.836033 |10001 |JASA MEDIS | |25000.00
10.836033 | |OBAT RESEP FARMASI NO : 3137 |F |0.00
10.836032 | |ADMINISTRASI | |0.00
10.836032 |10004 |JASA MEDIS | |25000.00
10.836032 | |PEMERIKSAAN RADIOLOGI NO 0932.1|R |15000.00
10.836034 |10604 |JASA MEDIS | |25000.00
10.836034 | |PEMERIKSAAN RADIOLOGI NO 0932.1|R |20000.00
I know my table needs to be normalized but I can't change the database since I have no right do so.
Problem is how to get result like this:
Doctor_ID |medicine |radiology
10004 |2000.00 |15000.00
10001 |0.00 |0.00
10604 |0.00 |20000.00
PM='F' as medicine and PM='R' as radiology
SELECT doctor_id, SUM(medicine) medicine, SUM(radiology) radiology
FROM (
SELECT MAX(doctor_id) doctor_id,
SUM(IF(pm='F', cost, NULL)) medicine,
SUM(IF(pm='R', cost, NULL)) radiology
FROM my_table
GROUP BY Trans_No
) t
GROUP BY doctor_id
See it on sqlfiddle.