6

I'm trying to get all the wins per team, however, SQL decides to throw an error

enter image description here

The following query is being executed:

SELECT `t`.`teamcode`, COUNT(*) AS `gewonnen` FROM `Team` `t` INNER JOIN `Wedstrijd` `w` ON `w`.`teamthuis` = `t`.`teamcode` GROUP BY `w`.`teamthuis` HAVING `w`.`scorethuis` > `w`.`scoreuit` #1054 - Unknown column 'w.scorethuis' in 'having clause' 

Without aliases:

SELECT `Team`.`teamcode`, COUNT(*) AS `gewonnen` FROM `Team` INNER JOIN `Wedstrijd` ON `Wedstrijd`.`teamthuis` = `Team`.`teamcode` GROUP BY `Wedstrijd`.`teamthuis` HAVING `Wedstrijd`.`scorethuis` > `Wedstrijd`.`scoreuit` #1054 - Unknown column 'Wedstrijd.scorethuis' in 'having clause' 
7
  • 2
    Are you sure that Wedstrijd has a column with the name scorethuis? Commented Dec 15, 2013 at 14:44
  • @MahmoudGamal Well pretty sure, check the image ;) Commented Dec 15, 2013 at 14:45
  • 1
    @user2196728 It's not the aliases, tried it without Commented Dec 15, 2013 at 14:45
  • Apart from the fact that the having clause does not do what you think it does, is the column scorethuis or scorehuis? Commented Dec 15, 2013 at 14:48
  • 2
    Do not understand the downvote here. I'm stumped by this error too. Was really curious on the reason behind it. Commented Dec 15, 2013 at 15:11

2 Answers 2

13

There is no need to use HAVING. Try WHERE instead:

SELECT `t`.`teamcode`, COUNT(*) AS `gewonnen` FROM `Team` `t` INNER JOIN `Wedstrijd` `w` ON `w`.`teamthuis` = `t`.`teamcode` WHERE `w`.`scorethuis` > `w`.`scoreuit` GROUP BY `w`.`teamthuis` 
Sign up to request clarification or add additional context in comments.

4 Comments

Yep that's it, thanks, could you explain why having doesn't work in this case?
@Mazzy I think this is because the column scorethuis is not included in the GROUP BY, the error is misleading actually :)
I believe it is because I'm performing scorethuis > scoreuit on EVERY row and not on the actual group :)
This solution only worked for me, but only when I had the WHERE clause before the GROUP BY clause.
0

I think if you had select w.scorethuis w.scoreuit both in select statement then 'Having;' would work. But I faced the same problem and I resolved it by the above way.

SELECT `t`.`teamcode`, COUNT(*),***`w`.`scorethuis`, `w`.`scoreuit`*** AS `gewonnen` FROM `Team` `t` INNER JOIN `Wedstrijd` `w` ON `w`.`teamthuis` = `t`.`teamcode` GROUP BY `w`.`teamthuis` HAVING `w`.`scorethuis` > `w`.`scoreuit` 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.