sql server - SQL select join the row with max (arithmatic(value1, value2)) -
i trying make trade system people can make offer on items want. there 2 currencies in system, gold , silver. 100 silver = 1 gold. note people can make offers same price others, there duplicate highest offer price.
table structure looks this
trade table id tradeoffer table id userid tradeid references trade(id) goldoffer silveroffer
i want display user list of trades sorted highest offer price whenever search constraint.
the ideal output similar this
trade.id tradeoffer.id highestgoldoffer highestsilveroffer userid
where highestgoldoffer
, highestsilveroffer
value of goldoffer
, silveroffer
column of offer
highest (goldoffer * 100 + silveroffer) , userid
user made offer
i know can run 2 separate queries, 1 retrieve trades satisfies constraint , extract id run query highest offer, perfectionist prefer 1 sql instead of two.
i select offers (goldoffer * 100 + silveroffer) = max (goldoffer * 100 + silveroffer) possibly return duplicated trade if there multiple people offered same price. there nobody offered on trade yet goldoffer , silveroffer empty, still show trade no offer when happened.
hope made myself clear , help
model , test data
create table trade (id int) create table tradeoffer ( id int, userid int, tradeid int, goldoffer int, silveroffer int ) insert trade values (1), (2), (3) insert tradeoffer values (1, 1, 1, 10, 15), (2, 2, 1, 11, 15), (3, 1, 2, 10, 16), (4, 2, 2, 10, 16)
query
select [tradeid], [tradeofferid], [highestgoldoffer], [highestsilveroffer], [userid] ( select t.id [tradeid], toffer.id [tradeofferid], toffer.goldoffer [highestgoldoffer], toffer.silveroffer [highestsilveroffer], toffer.[userid], rank() on ( partition t.id order (([goldoffer] * 100) + [silveroffer]) desc ) [rank] trade t left join tradeoffer toffer on toffer.tradeid = t.id ) x [rank] = 1
result
Comments
Post a Comment