从未标准化的表中通过ID从列中获取SUM?

时间:2012-11-30 15:03:55

标签: mysql sum database-normalization

我有一家医院的数据库。在表格中有1个或多个交易号码,几乎所有交易号码只包含1个医生ID。该表尚未正常化。

数据如下所示:

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

我知道我的桌子需要规范化,但我无法更改数据库,因为我没有这样做。

问题是如何得到这样的结果:

Doctor_ID  |medicine    |radiology
10004      |2000.00     |15000.00
10001      |0.00        |0.00
10604      |0.00        |20000.00

PM ='F'作为药物,PM ='R'作为放射学

1 个答案:

答案 0 :(得分:1)

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

sqlfiddle上查看。