2016-12-12 17 views
0

ユーザテーブルの最大値に応じて1列によってグループ化し、個別の行を示す結果は、第二のカラム

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

? (その答えは製品によって異なる場合があります) – jarlh

+0

mysql dbms 5.xバージョン –

答えて

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

各リストの最高入札価格を返す派生テーブル(サブクエリ)があります。その結果、参加しても、ユーザーと参加:

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 
0

これが何をすべき:あなたが使用しているDBMS

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 
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