【问题标题】:SQL-Server: Summing a column while ignoring duplicate recordsSQL-Server:在忽略重复记录的同时对列求和
【发布时间】:2021-04-17 22:49:34
【问题描述】:

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

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

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

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

【问题讨论】:

  • 重复值听起来像是您的数据库中有问题

标签: sql sql-server sum duplicates distinct


【解决方案1】:

您可以使用两个级别的聚合或聚合与窗口函数:

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;

【讨论】:

  • 假设我的表名是 table_1 这是正确的语法吗? select custid, sum(amount) from (select table_1.*, row_number() over (partition by custid, transid order by transid) as seqnum from table_1 ) t where seqnum = 1;我收到以下错误 Msg 8120, Level 16, State 1, Line 22 列 't.custid' 在选择列表中无效,因为它既不包含在聚合函数或 GROUP BY 子句中。
【解决方案2】:

在聚合之前应用 DISTINCT:

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

【讨论】:

    猜你喜欢
    • 2018-04-26
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    • 2022-12-07
    • 2019-08-08
    • 2013-06-25
    • 2017-12-21
    • 1970-01-01
    相关资源
    最近更新 更多