sql server - Second largest bid in auction -


i need produce report shows second highest bidders various auctions. sample data single auction included below. how might write query return:

  • the auctionid.
  • the second highest bid.
  • the time difference between highest bid , second highest bid.


auctionid   bidamount   biddate             userid 15410       42559.23    16/11/2012 19:38    41 15410       23613.12    16/11/2012 19:16    2 15410       18000.00    16/11/2012 19:13    16 15410       15249.94    16/11/2012 18:38    9 15410       9813.50     16/11/2012 18:36    7 15410       5341.58     16/11/2012 18:16    7 

try row_number function:

declare @t table     (       auctionid int ,       amount money ,       biddate datetime ,       userid int     )  insert  @t values  ( 15410, 42559.23, '20121116 19:38', 41 ),         ( 15410, 23613.12, '20121116 19:16', 2 ),         ( 15410, 18000.00, '20121116 19:13', 16 ),         ( 15410, 15249.94, '20121116 18:38', 9 ),         ( 15410, 9813.50, '20121116 18:36', 7 ),         ( 15410, 5341.58, '20121116 18:16', 7 );      cte           ( select   * ,                         row_number() on ( partition auctionid order amount desc ) rn                    @t              )     select  c1.auctionid ,             c2.amount ,             datediff(ss, c1.biddate, c2.biddate) diffinseconds        cte c1             join cte c2 on c2.auctionid = c1.auctionid                            , c1.rn = 1 , c2.rn = 2 

output:

auctionid   amount   diffinseconds 15410       23613.12 -1320 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -