首页 > 解决方案 > 我需要加入两个表。第一个表有一些带有 id 列的数据,第二个表有相同 id 的数据,但会有多个 id

问题描述

表格1

workid est_amt  amount_spent
1       1000     50
2       200     100

表 2

workid  totalDeduction  amt_payble
1        30              20 
1        30              20 
2        25              30 

代码

select count(a.workid),a.est_amt,SUM(a.amt_spent + b.total_deductions + b.amt_payable) from table1 a left join table2 b on a.workid = b.workid

结果应该是

total_works amount_paid   balance_amount_to_pay
2            305          695 

我得到这个结果

total_works amount_paid   balance_amount_to_pay
3            305          695 

标签: sqlsql-server

解决方案


usingdistinct()将仅获取唯一 ID 的计数。

select count(distinct a.workid)
    ,SUM(a.est_amt)
    ,SUM(a.amt_spent + b.total_deductions + b.amt_payable) 
from table1 a 
left join table2 b on a.workid = b.workid

推荐阅读