从未经规范化的表中按ID获取列的SUM?

时间:2012-11-24 11:58:59

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

如何从PM列值为F的医生那里获得医生ID和费用总和?

我无法更改数据库,因为它已经有超过十万个交易。

2 个答案:

答案 0 :(得分:1)

使用子查询创建"表"将Trans_No映射到Doctor_ID。然后使用此子查询加入您的真实表,以便为每个事务行创建一个Doctor_ID。然后,您可以执行WHEREGROUP 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

答案 1 :(得分:0)

这为您提供了Trans_No,Doctor_ID和Cost的标准化版本:

select
  Trans_No,
  max(Doctor_ID) as Doctor_ID,
  max(case when PM="F" then Cost end) as Cost
from
  your_table
group by
  Trans_No

然后你必须按Doctor_ID进行分组:

Select Doctor_ID, sum(Cost)
From (
  select
    Trans_No,
    max(Doctor_ID) as Doctor_ID,
    max(case when PM="F" then Cost end) as Cost
  from
    your_table
  group by
    Trans_No) your_table
Group by Doctor_ID