简体   繁体   中英

select sum where condition is true and count > 3

I have two tables.

  • FootballPlayers with columns Id_footballplayer, Last_Name, Fisrt_Name, Age
  • Transfers 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

Since this is a group scenario, after the GROUP 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM