Search code examples
mysqlsumdatabase-normalization

Obtain the SUM from a column by ID from a table that isn't normalized?


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   |10001      |JASA MEDIS                     |   |25000.00
10.836032   |           |OBAT RESEP FARMASI NO : 3138   |F  |10000.00

How can I get doctor ID and the SUM of cost from that doctor where the PM column value is F?

I can't change the database because it already has more than a hundred thousand transactions.


Solution

  • Use a subquery to create a "table" mapping Trans_No to Doctor_ID. Then join your real table with this subquery to have a Doctor_ID for every transaction row. Then you can do your WHERE and GROUP BY.

    SELECT tdoc.Doctor_ID, SUM(Cost) FROM your_table
    JOIN (
      SELECT Trans_No, Doctor_ID FROM your_table WHERE Doctor_ID <> ''
      GROUP BY Trans_No, Doctor_ID
    ) tdoc ON tdoc.Trans_No = your_table.Trans_No
    WHERE PM = 'F'
    GROUP BY tdoc.Doctor_ID