简体   繁体   中英

SQl query calculations across multiple tables

OK, I have 3 database tables at the moment:

  • users
    • id: 1, 2
    • name: User1, User2
  • companies
    • id: 1, 2, 3
    • share_price: 10.00, 0.45, 5.98
  • portfolios
    • user_id: 1, 1, 2
    • company_id: 1, 2, 1
    • amount_of_shares: 200, 100, 30

Just so you know, this is for a basic stock market simulation. I need to get the top 5 users based on their total portfolio values, which are calculated as such:

companies.share_price * portfolios.amount_of_shares

Keeping in mind that 1 user can have stock from multiple companies in his portfolio, it seems like a waste to select all the data and then loop through it in PHP, because theoretically I could have about 200 companies... So I was wondering if it's possible to write an SQL query that calculates the value of each companie's stock owned and then sums all of those values up to produce only one variable, so I can do ORDER BY and LIMIT 5 (get the Top5 performers)

EDIT: I'm using CodeIgniter for this project, if that makes a difference.

SELECT *, SUM(amount_of_shares*c.share_price) as total FROM `portfolios`
LEFT JOIN companies c ON c.id = portfolios.company_id
GROUP BY `user_id`
ORDER BY total DESC
LIMIT 5
select u.name, sum(c.share_price * p.amount_of_shares) as total
from portfolios p
inner join companies c on p.company_id = c.id
inner join users u on p.user_id = u.id
group by u.name
order by total desc
LIMIT 5

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