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)
編集私はSINGLEの連絡先の結果を得ることができましたが、すべての連絡先に対してそれを試してみたいと思います。
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;