即使按

时间:2017-11-20 19:09:05

标签: sql

我似乎无法使用group by找出一个简单的SUM()场景。

我试图比较来自两个不同表格的计费总额与付费总额。我现在拥有的是:

SELECT  
  claimamount,
  SUM(billing_entries.paidamount)
FROM customers.billing_entries, customers.claim_items
WHERE
    lastclaimid = 2132206 
    AND billing_entries.lastclaimid = claim_items.claimid
GROUP BY  claimid, claimamount;

对于这个特定情况,claimamount是256.45,总支付是244.44

当我运行时,我得到以下内容:

256.4500 ; 977.7600

索赔中有4个条目,每次都是SUM并返回4 *它们的实际总和244.44。

我从中拉出的两个表的示例数据:

claim_items: claimid = 2132206 claimamount = 256.45

billing_entries:

ENTRYID(1) 27136421 paidamount(1) 25.64

ENTRYID(2) 27136423 paidamount(2) 102.5800

ENTRYID(3) 26803842 paidamount(3) 102.5800

ENTRYID(4) 26803839 paidamount(4) 13.64

他们都有相同的lastclaimid 2132206

以下是数据的一些截图

claim_items

billing_entries

billingentrygroupid | claimamount | claimid | clientid |入口金额|入口数量| entryunit |入境单位id |亚麻布| organizationid |程序代码|收到| renderingprovidercontactid | renderingproviderid | renderingproviderotherid | SENTON
-------------------- + ------------- + --------- + ----- ----- + ------------- + --------------- + ----------- + - ------------- + ---------- + ------------ + ------------ ---- + --------------- + --------------------- + ------- --------------------- + --------------------- + ------ -------------------- + --------------------            24015783 | 256.45 | 2132206 | 174491 | 102.58 | 4.00 |联合国| 51.29 | 12483241 | 2 | 168717 | 0365T | 2017-10-17 16:49:47 | 370211 | | 622843915 | 2017-10-06 18:58:57            24302220 | 256.45 | 2132206 | 174491 | 25.65 | 1.00 |联合国| 51.29 | 12483242 | 3 | 168717 | 0364T | 2017-10-17 16:49:47 | 370211 | | 622843915 | 2017-10-06 18:58:57            24302220 | 256.45 | 2132206 | 174491 | 102.58 | 4.00 |联合国| 51.29 | 12483243 | 4 | 168717 | 0365T | 2017-10-17 16:49:47 | 370211 | | 622843915 | 2017-10-06 18:58:57            24015783 | 256.45 | 2132206 | 174491 | 25.65 | 1.00 |联合国| 51.29 | 12483244 | 1 | 168717 | 0364T | 2017-10-17 16:49:47 | 370211 | | 622843915 | 2017-10-06 18:58:57

2 个答案:

答案 0 :(得分:1)

不确定这是否有帮助,但请尝试将子查询中支付的金额分组:

select
    claimid, claimamount, sum_paid 
from
    customers.claim_items c inner join
    (select
        lastclaimid,
        sum(paidamount) as sum_paid
    from
        customers.billing_entries
    group by
        lastclaimid) p on
    c.claimid = p.lastclaimid

答案 1 :(得分:0)

使用您的查询,我自己创建了查询

Select  
  ci.claimamount,
  sum(be.paidamount)
from 
   customers.billing_entries be 
   inner join (select distinct(claimid), claimamount from customers.claim_items) as ci 
      on be.lastclaimid = ci.claimid
      and be.lastclaimid = 2132206 
group by ci.claimamount;

我得到的正确数据为ouptut,即claimamount 256.45和总paynamount为244.44。 编辑 - 根据提供的表格的屏幕截图更新答案。