I have two tables.
FootballPlayers
with columns Id_footballplayer, Last_Name, Fisrt_Name, AgeTransfers
with columns Id_transfer, Name_club, price, date, acceptance (yes or no), code_footballplayer
How can I write a SQL query to select the last names of the players and the sum of the successful transfers carried out by them, the number of which exceeds 3?
I already wrote a query that displays the total amount of all successful transfers for each player
SELECT FootballPLayers.Last_Name, SUM(CASE acceptance WHEN 'yes' THEN price ELSE 0 END) AS amount_price FROM FootballPlayers INNER JOIN Transfers ON FootballPlayers.ID_footballplayer = Transfers.code_footballplayer GROUP BY FootballPlayers.Last_Name;
But I don’t know how to add a condition if the number of successful transfers is more than 3
Advertisement
Answer
Since this is a group scenario, after theGROUP BY
you probably want:
HAVING COUNT(1) > 3
The HAVING
clause works very similarly to WHERE
, but is applied differently.
An alternative would be the sub-query:
SELECT * FROM ( SELECT FootballPLayers.Last_Name, SUM(CASE acceptance WHEN 'yes' THEN price ELSE 0 END) AS amount_price, COUNT(1) AS [Transfers] FROM FootballPlayers INNER JOIN Transfers ON FootballPlayers.ID_footballplayer = Transfers.code_footballplayer GROUP BY FootballPlayers.Last_Name ) x WHERE x.Transfers > 3