用户表:
id | name
1 | sai
2 | krishna
出价表:
bid_id | listing_id | user_id | bid_amount
1 | 999 | 1 | 100
2 | 999 | 2 | 200
3 | 999 | 2 | 300
所以我希望得到的结果就是这个
bid_id | listing_id | bid_amount | name
1 | 999 | 100 | sai
3 | 999 | 300 | krishna
我希望结果按listing_id
分组,但只为bid_amount
为最大值的用户显示不同的行
答案 0 :(得分:1)
SELECT COALESCE(b1.bid_id, -1),
COALESCE(b1.listing_id, -1),
COALESCE(b1.bid_amount, 0),
u.name
FROM user u
LEFT JOIN bid b1
ON u.id = b1.user_id
LEFT JOIN
(
SELECT user_id, MAX(bid_amount) AS bid_amount
FROM bid
GROUP BY user_id
) b2
ON b1.user_id = b2.user_id AND
b1.bid_amount = b2.bid_amount
答案 1 :(得分:1)
有一个派生表(子查询),它返回每个列表的最高出价。加入该结果并加入用户:
select b1.bid_id, b1.listing_id, b2.bid_amount, u.name
from bid b1
join (select listing_id, max(bid_amount) as max_bid_amount
from bid
group by listing_id) b2
on b1.listing_id = b2.listing_id and b1.bid_amount = b2.max_bid_amount
join user u on b.user_id = u.id
答案 2 :(得分:0)
这应该做:
SELECT bid.bid_id, bid.listing_id, bid.bid_amount, users.name
FROM bid bid
INNER JOIN user users ON bid.user_id = users.id
INNER JOIN (SELECT MAX(bid.bid_amount) AS MaxBid, bid.user_id
FROM bid bid
GROUP BY bid.user_id
) MaxBids ON bid.bid_amount = MaxBids.MaxBid
答案 3 :(得分:0)
Select D1.*
From (
Select D1.id, D1.name, D2.bid_id, D2.listing_id, D2.bid_amount,
Rank() Over (Partition By D1.id
order by D2.bid_amount desc
) As Rank
From @table1 D1
Inner Join @table2 D2
On D1.id = D2.user_id
) D1
Where D1.Rank =1