连接表的唯一行的总和

时间:2014-04-19 13:17:23

标签: mysql sql

我有3张桌子。 practicesadjustmentsclaims 我需要使用其他列adjustments.amount + count(claims.id)

选择所有实践

这是我的查询。

SELECT 
 practices.*,
 (
   SUM(adjustments.amount) + count(claims.id)
 ) as accurred_fees
  INNER JOIN adjustments ON adjustments.practice_id = practices.id 
  INNER JOIN claims ON claims.practice_id = practices.id
 GROUP BY practices.id

在我的数据库中,我有1次练习,20次声明和1次调整,金额等于2。查询中SUM(eligible_fee_adjustments.amount)总是返回40,我猜它是2 * count(claims.id),我不知道它为什么会这样。能帮我找到解决方案吗?提前致谢

1 个答案:

答案 0 :(得分:3)

您有两个不同维度的连接问题,因此行数相乘。您可以通过预先聚合数据来解决此问题。以下将解决此特定问题:

SELECT p.*,
       (SUM(a.amount) + c.cnt) as accurred_fees
FROM practices p INNER JOIN
     adjustments a
     ON a.practice_id = p.id INNER JOIN
     (SELECT practice_id, count(*) as cnt
      FROM claims c
      GROUP BY practice_id
     ) c
     ON c.practice_id = p.id
GROUP BY p.id;

你也应该预先调整调整:

SELECT p.*,
       (a.amount + c.cnt) as accurred_fees
FROM practices p INNER JOIN
     (SELECT practice_id, SUM(amount) as amount
      FROM adjustments a
      GROUP BY practice_id
     ) a
     ON a.practice_id = p.id INNER JOIN
     (SELECT practice_id, count(*) as cnt
      FROM claims c
      GROUP BY practice_id
     ) c
     ON c.practice_id = p.id
GROUP BY p.id;

您可能需要考虑LEFT OUTER JOIN而不是INNER JOIN,以便获得所有实践,即使是那些可能缺少调整或声明的实践。