我希望能够获得使用 MySql 的每个联系人的最新 3 CampaignId 的平均分数。
[id], [ContactId], [CampaignId], [Score]
1 1 100 5
2 1 100 7
3 1 101 1
4 1 102 3
5 1 103 2
6 1 103 2
7 2 100 1
8 2 103 2
9 3 103 1
10 3 104 3
11 3 105 2
12 3 106 4
13 4 101 5
所以结果将是: -
[ContactId], [AvgScore] (worked out by)
1 2.66 (1 + 3 + 2 + 2 ) /3
2 1.50 (1 + 2) / 2 (as there are only two campaigns)
3 3.00 (3 + 2 + 4) / 3
4 5.00 (5) / 1 (as there is only one campaign)
编辑我已经设法获得了单个联系人的结果,但也想尝试为所有联系人解决问题。
select ContactId, sum(Score), sum(Count)
from (
select
ContactId, CampaignId, sum(Score) Score, count(distinct CampaignId) Count
from stats
where
ContactId = 1
group by
CampaignId, ContactId
order by CampaignId DESC limit 3) a;