2015-10-20 51 views
1

如果没有历史记录只显示源表(Billings)中的相同信息,我需要根据其最后一条记录(Billings_History)获取每个帐单的净总数。获取mysql查询中历史表的净总数

比林斯

BILLCOD TOTAL 
BILL01 15.00 
BILL02 10.00 
BILL03 15.00 
BILL04 26.00 
BILL05 294.00 

Billings_History

HISTORYCOD BILLCOD TOTAL 
H001  BILL01 36.00 
H002  BILL01 5.00 -- USE Latest HISTORYCOD in case when BILLCOD is duplicated 
H003  BILL03 50.00 
H004  BILL05 204.00 

我需要这个结果

BILL01 -10.00 
BILL03 35.00 
BILL05 -90.00 

任何想法?

回答

1

这里是由@jarlh给出的解决方案替代:

SELECT b.BILLCOD AS BILLCOD, t.TOTAL - b.TOTAL AS TOTAL 
FROM Billings b INNER JOIN 
(
    SELECT bh1.HISTORYCOD, bh1.BILLCOD, bh1.TOTAL 
    FROM Billings_History bh1 INNER JOIN 
    (
     SELECT BILLCOD, MAX(HISTORYCOD) AS MAXHISTORYCOD 
     FROM Billings_History 
     GROUP BY BILLCOD 
    ) bh2 
    ON bh1.HISTORYCOD = bh2.MAXHISTORYCOD AND bh1.BILLCOD = bh2.BILLCOD 
) t 
ON b.BILLCOD = t.BILLCOD 
+1

再次感谢你,你的回答解决我的问题。 –

1

子选择使用NOT EXISTS回到每个BILLCOD最新TOTALBillings_History表。

这个结果是右边的表格到LEFT JOIN。如果右侧表格中没有行,则使用COALESCE将值设置为0。

select b.BILLCOD, coalesce(bh.TOTAL,0) - b.TOTAL 
from Billings b 
left join (select BILLCOD, TOTAL 
      from Billings_History bh1 
      where not exists (select 1 from Billings_History bh2 
          where bh2.BILLCOD = bh1.BILLCOD 
           and bh2.HISTORYCOD > bh1.HISTORYCOD)) bh 
    on b.BILLCOD = bh.BILLCOD