如何将礼品金额与重复礼品相加

问题描述 投票:0回答:2

我有一张这样的桌子 -

GiftImpID  GiftAmt   Category
12345       12.00    Donation
12345       12.00    Donation
56789       10.00    Donation
56789       10.00    Donation
7890         5.00    Sale

所以我需要为每个类别添加DISTINCT(GiftImpID)和GiftAmt。

我需要得到

GiftAmt   Category
22.00     Donation
5.00      Sale

我试过了

Select SUM(Giftamt), Category From #MDevReport 
Where GiftImpID
IN(Select DISTINCT(giftImpID) FROM #MDevReport) 
GROUP BY Category

但我仍然在总和中添加重复项...

sql group-by distinct
2个回答
0
投票

使用子查询:

select sum(GiftAmt), Category 
from (select distinct GiftImpID, GiftAmt, Category 
      from #MDevReport 
     ) t
group by Category; 

0
投票

使用两个级别的聚合:

select category, sum(GiftAmt)
from (select Category, GiftImpID, avg(GiftAmt) as GiftAmt
      from #MDevReport 
      group by Category, GiftImpID
     ) dr
group by category;

然后,修复您的数据模型。显然,重复每行中的值是不合适的。

© www.soinside.com 2019 - 2024. All rights reserved.