Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

sql - Return the names of people that have half the wealth of the richest person

For an assignment i must combine 3 tables and write a query that returns the names of all people that have less than half of the wealth of the richest person. We define the wealth of a person as the total money on all of his/her accounts.

The 3 tables are:


Persons

id | name | address | age | eyeColor | gender


BankAccounts

id | balance


AccountOf

id | person_id → Persons | account_id → BankAccounts

I know how to use te SUM() function and the MAX() function, but combining them is a pain in my ass. There is also someone without an bankaccount. Does anyone know how to do this assignment or can give me a hint?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Not to give it away, since it's an assignment and that kind of ruins the whole thing, but... you'll need to find the sum(balance) for the richest person, which would be the max of all the persons' sum(balance). This will look something like:

SELECT
    max(personbalance)
FROM
    (
        Select 
            sum(balance)
        FROM
            persons
            join accountof
            join bankaccounts
        GROUP BY persons.id
    )subForSum

This will just be a subquery in your main query, but it should give you enough direction to slap the rest of it together. When in doubt with these things, just subquery and subquery and subquery. You can clean it up after you get the answer you expect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...