我需要制作一份报告,显示各种拍卖的第二高出价者。下面列出了单次拍卖的样本数据。我如何编写一个返回的查询:
AuctionID
。
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
答案 0 :(得分:3)
尝试使用ROW_NUMBER
功能:
DECLARE @t TABLE
(
AuctionID INT ,
Amount MONEY ,
BidDate DATETIME ,
UserID INT
)
INSERT INTO @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 );
WITH cte
AS ( SELECT * ,
ROW_NUMBER() OVER ( PARTITION BY AuctionID ORDER BY Amount DESC ) AS rn
FROM @t
)
SELECT c1.AuctionID ,
c2.Amount ,
DATEDIFF(ss, c1.BidDate, c2.BidDate) DiffInSeconds
FROM cte c1
JOIN cte c2 ON c2.AuctionID = c1.AuctionID
AND c1.rn = 1 AND c2.rn = 2
输出:
AuctionID Amount DiffInSeconds
15410 23613.12 -1320
答案 1 :(得分:0)
在MSSQL中,您可以使用以下查询选择所需的条目:
SELECT * FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY BidAmount DESC) AS rownumber, <tablename>.*
FROM <tablename>
)
WHERE rownumber = 2