In my gaming application i have Teams and each Team can have any number of players, if a player participates in a match i am giving him 5 points. Each time the player participates in a match he will get 5 points added to his count.
my stored procedure takes TeamId as the input parameter.
Now i want to calculate the Total Participation points each team has got by month, but here the Participation Points each player has scored should be added to the last month in which the player has played the Match.
Lets say Team1 has Player1 and player1 has played total of 4 matches, 1 match in 04/2020 , 2 matches in 06/2020 and 1 match in 08/2020 , here for playing 4 matches Player1 of Team1 got 20 participation points and the last match Player1 played is in 08/2020 so all the 20 points should be added to 08/2020 for Team1
In the player table across each Player i have a [TotalMatchesPlayed] by each player, [TotalMatchesPlayed] * 5 will give me the [TotalParticipationPoints] for each player.
This should repeat for all the players in the Team.
SELECT DISTINCT TP.[TeamId], ISNULL(P.[TotalMatchesPlayed], 0) * 5 AS [ParticipationPoints], CAST(MONTH(PA.[ActivityDate]) AS VARCHAR(2)) AS [Month], CAST(YEAR(PA.[ActivityDate]) AS VARCHAR(4)) AS [Year] FROM [TeamPlayers] TP
INNER JOIN dbo.[Player] P
ON TP.[PlayerId] = P.[PlayerId]
INNER JOIN dbo.[PlayerActivity] PA
ON PA.[PlayerId] = P.[PlayerId] AND PA.[ActivityTypeId] = 14
WHERE TP.[TeamId] = 12
my issue with above query is [PlayerActivity] table has a row each time a player participates in a match, now i want to take only the latest date and add all the participation points to that month and year which i am not able to achieve
I tried adding ORDER BY PA.[ActivityDate] DESC but thts throwing an error
Order by items must appear in the select list if SELECT DISTINCT is specified.
my sample output should be as below
ParticipationPoints | Month | Year
50 03 2020
0 04 2020
20 05 2020
sample table designs and data in the below link.
Does this work for you:
SELECT
TP.[TeamId]
, SUM(ISNULL(P.[TotalMatchesPlayed], 0)) * 5 AS [ParticipationPoints]
, DATEPART(MONTH,PA.[ActivityDate]) AS [Month]
, DATEPART(YEAR,PA.[ActivityDate]) AS [Year]
FROM [TeamPlayer] TP
INNER JOIN dbo.[Player] P
ON TP.[PlayerId] = P.[PlayerId]
INNER JOIN dbo.[PlayerActivity] PA
ON PA.[PlayerId] = P.[PlayerId] AND PA.[PlayerActivityTyepId] = 14
WHERE TP.[TeamId]=45
GROUP BY TP.[TeamId], DATEPART(MONTH,PA.[ActivityDate]), DATEPART(YEAR,PA.[ActivityDate])
ORDER BY DATEPART(MONTH,PA.[ActivityDate]) DESC, DATEPART(YEAR,PA.[ActivityDate]) DESC