"Smart" way of summing results of a query?

Hi all!

In hacker news SQL project, section 4:

We’re asked to sum the score of the top users in hacker news (users with total score > 200).

The suggested way to do it is manually hardcode magic numbers into select clause and divide it by total score of all users.

That’s a bad way of doing it, isn’t it?

I tried to run the following query:

select sum(score) from hacker_news where score > 200;

It gives a total of 1412 which is the number we’re looking for (517+309+304+282).

Though it seems odd to me, since the database is handled by “per title” way, not “per user” (meaning I don’t know why sql sums the score of the top users rather than summing the top titles posted to the website).

Also, I don’t know how can I add a division operator here that works on the sum of all the posts, at least not without a variable.

I’d really like to hear an input about this!


1 Like

Remember: WHERE only filters rows
HAVING filters groups

I’m not following this bit here:

The “scores” column is an integer (see the schema).
In the previous query, you’re selecting two columns, user and the sum of scores, grouping by users who have a sum of scores greater than 200:

SELECT user, SUM(score)
FROM hacker_news
HAVING SUM(score) > 200