I have a table in my database whose structure is like this
sell_id(int) | car_id(int) | worth(int) | date(date) | selled(boolean)
Selled is a wrong 'sold'.
My table is like this
------------------------------
50 |50 |2405 | "2012-07-16" | false
51 |51 |9300 | "2014-10-07" | false
52 |52 |5963 | "2014-11-01" | false
53 |53 |2036 | "2014-09-19" | false
54 |54 |4770 | "2014-01-26" | false
55 |55 |11915| "2010-08-30" | true
Anyway, sell_id is the primary key of this table and a foreign key to a "mother" table. car_id refers to another table as well. Worth is the amount of money a seller sold or bought a car. Date is just when and selled is a boolean to specify whether the seller sold or bought the car. If it is true then he did sell it. Otherwise he bought it.
Now i want to find the user who has made the most value out of selling/buying. This means that he must be the one to have the selled-bought.But i cant figure out the right query.
this query gives me the values of only selling.
select sell_id, sum(worth), selled
from sellers
where(selled=true)
group by sell_id, selled
Some desired result for example would be:
sell_id | total_profits(max)
---------------------------
51 | 2000
where total_profits would be the maximum worth(where selled=true)-worth(where selled=false)
Any ideas would be really helpfull. Thanks :)
i finally found the answer to my own question. the correct query is :
select sell_id, (sum(worth) - (select sum(worth)
from sellers where selled=false group by sell_id
order by sum limit 1)) as final from sellers
where selled=true
group by sell_id order by final desc limit 1