获取SQL Server中按不同字段分组的总和

获取SQL Server中按不同字段分组的总和,sql,sql-server,tsql,Sql,Sql Server,Tsql,这是我的桌子 PayerID PaymentID Amount 1 8386 5827.14 1 8386 5827.14 1 8386 5827.14 1 8387 4464.68 1 8387 4464.68 1 8387 4464.68 2 8388 1482.57 2 8388 1482.57 2 8388 1482.57

这是我的桌子

 PayerID PaymentID Amount

    1   8386    5827.14
    1   8386    5827.14
    1   8386    5827.14
    1   8387    4464.68
    1   8387    4464.68
    1   8387    4464.68
    2   8388    1482.57
    2   8388    1482.57
    2   8388    1482.57
    2   8388    1482.57
    2   8388    1482.57
    2   8388    1482.57
    2   8388    1482.57
    2   8388    1482.57
    2   8388    1482.57
我想要不同PaymentID组的PayerID的金额总和,如下所示

payerID AmountSum
1        5827.14 + 4464.68
2         1482.57
使用
SUM(DISTINCT)

此解决方案假定
金额
对于不同的
付款ID
是唯一的


更一般的做法:

SELECT PayerId, SUM(Amount) AS AmountSum
FROM (SELECT DISTINCT PayerID, PaymentID, Amount
      FROM tab) sub
GROUP BY PayerId
使用
SUM(DISTINCT)

此解决方案假定
金额
对于不同的
付款ID
是唯一的


更一般的做法:

SELECT PayerId, SUM(Amount) AS AmountSum
FROM (SELECT DISTINCT PayerID, PaymentID, Amount
      FROM tab) sub
GROUP BY PayerId

您可以使用以下行号进行查询:

Select PayerId, sum(amount) from (
    Select *, RowN = Row_Number() over(partition by Payerid, PaymentId, Amount order by Amount) from #payerdata
) a
where a.RowN = 1
group by PayerId
+---------+-----------+
| PayerId | AmountSum |
+---------+-----------+
|       1 |  10291.82 |
|       2 |   1482.57 |
+---------+-----------+
输出如下:

Select PayerId, sum(amount) from (
    Select *, RowN = Row_Number() over(partition by Payerid, PaymentId, Amount order by Amount) from #payerdata
) a
where a.RowN = 1
group by PayerId
+---------+-----------+
| PayerId | AmountSum |
+---------+-----------+
|       1 |  10291.82 |
|       2 |   1482.57 |
+---------+-----------+

您可以使用以下行号进行查询:

Select PayerId, sum(amount) from (
    Select *, RowN = Row_Number() over(partition by Payerid, PaymentId, Amount order by Amount) from #payerdata
) a
where a.RowN = 1
group by PayerId
+---------+-----------+
| PayerId | AmountSum |
+---------+-----------+
|       1 |  10291.82 |
|       2 |   1482.57 |
+---------+-----------+
输出如下:

Select PayerId, sum(amount) from (
    Select *, RowN = Row_Number() over(partition by Payerid, PaymentId, Amount order by Amount) from #payerdata
) a
where a.RowN = 1
group by PayerId
+---------+-----------+
| PayerId | AmountSum |
+---------+-----------+
|       1 |  10291.82 |
|       2 |   1482.57 |
+---------+-----------+

按payerID从表组中选择金额(不同金额)
按payerID从表组中选择金额(不同金额)
有时金额相同,付款ID不同。与8386和8387一样,可以将金额设置为5827.14,因此应基于PaymentID@Niyas如果您的问题已经解决,您可以接受我的答案:)有时金额相同,付款ID不同。与8386和8387一样,可以将金额设置为5827.14,因此应基于PaymentID@Niyas如果你的问题已经解决,你可以接受我的答案:)