这是我的表
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
我希望通过PayerID支付不同PaymentID组的金额,如下所示
payerID AmountSum
1 5827.14 + 4464.68
2 1482.57
答案 0 :(得分:4)
使用SUM(DISTINCT)
SELECT PayerId, SUM(DISTINCT Amount) AS AmountSum
FROM tab
GROUP BY PayerId;
此解决方案假定Amount
对于不同的PaymentId
是唯一的。
更一般的方法:
SELECT PayerId, SUM(Amount) AS AmountSum
FROM (SELECT DISTINCT PayerID, PaymentID, Amount
FROM tab) sub
GROUP BY PayerId
答案 1 :(得分:0)
您可以使用row_number进行查询,如下所示:
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 |
+---------+-----------+