SQL-服务器:在忽略重复记录的同时对列求和

SQL-Server: Summing a column while ignoring duplicate records

我有一个 table 包含具有重复值的行。

TransID--CustID-- Date-----Amount
5217151 212671  2020-10-31  30.00
5217151 212671  2020-10-31  30.00
5219330 212671  2020-11-30  30.00
5219330 212671  2020-11-30  30.00

我需要对“金额”列求和,但忽略交易 ID 重复的所有行。例如,客户 212671 的总金额为 60.00。我曾尝试使用 Select Distinct,但在一列上使用不同但在另一列上求和时,我无法弄清楚执行此操作的正确语法。

这是我第一次 post 在 Whosebug 上,我发现很难格式化我的文本并粘贴到数据的实际屏幕截图中,所以请原谅。谢谢。

您可以使用两级聚合或具有 window 函数的聚合:

select custid, sum(amount)
from (select t.*,
             row_number() over (partition by custid, transid order by transid) as seqnum
      from table_1 t
     ) t
where seqnum = 1;

聚合前应用 DISTINCT:

with cte as
 (
   select distinct TransID, CustID, Amount
   from mytable
 )
select CustId, sum(Amount)
from cte
group by CustId