2

Some things in lecture and in my lab assignment were not explained very well. I am having trouble displaying the correct information. Here is the database info, simply a reference for you to help me. The database tables info This is the query that I am trying to execute The postgresql php select statement

This results in this SQl error being throwned

Connected to database! Query failed: ERROR: column "city.name" must appear in the GROUP BY clause or be used in an aggregate function LINE 3: city.name ^

Now if I do add city.name into the GROUP BY clause, it returns 4096 rows! I dont want that to happen, the results have to be group by country name which is 232 rows. I simply want to display the country name, city name, and the city with the highest population in that country. City name is throwing me off, Im guessing there is a more complicated more syntax heavy solution. Thanks for any help you can provide. -Tom Reese

1 Answer 1

1

You need something like this:

select
        country.name,
        city.name,
        mp.maxpop
from
        lab6.country,
        lab6.city,
        (select
                country_code,
                max(population) as maxpop
        from
                lab6.city
        group by
                country_code
        ) mp
where
        country.country_code=mp.country_code and
        country.country_code=city.county_code and 
        mp.maxpop=city.population

notes:

  • This can give you more result/county.
  • Your original query doesn't work because in ansi sql you can't return only aggregated or group by expressions from a "group by" query. (As the error mentions)
Sign up to request clarification or add additional context in comments.

5 Comments

ok this makes more sense the professor did provide a example that was very similar to this but it was only on one table, i could not connect the dots. Thanks Lajos
welcome. There are other methods to achieve the same result, but they are not ansi sql: postgresql.org/docs/8.4/static/tutorial-window.html In school probably you should practice the learned methods.
I'm pretty sure window functions are standard SQL. I think your first where is supposed to be a from and you might want to do something about those nasty implicit joins.
You are right... When I learnt sql these window functions not existed in practice... :-)
yeah i fixed the where to a from, every thing is working, here is proof imgur.com/gS1mwmf

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.