如何通过查询按顺序获取n个顶级记录

时间:2017-03-22 14:01:16

标签: sql sql-server sql-server-2014

我使用以下查询来检索交易,但每个用户只需要前2条记录

SELECT  bt.FromID, bt.ToID, u.Username, bt.Amount, bt.ToOpeningBal, bt.ToClosingBal, bt.CreatedDate AS TransferDate, u.CreatedDate AS RETLCreatedDate
FROM   BalanceTransfer AS bt INNER JOIN Users AS u ON bt.ToID = u.ID
WHERE  u.CreatedDate BETWEEN '2017-01-04 00:00:14.1400000' AND '2017-01-10 00:00:14.1400000'
AND ( bt.ToOpeningbal = 0 or bt.ToOpeningbal = 200)
ORDER BY bt.CreatedDate



Username  | Amount |    ToOpeningBal|   ToClosingBal |  TransferDate
----------|--------|----------------|----------------|----------------
ABC       |   2044 |   0            |  2044          | 2/18/17 11:00 AM
ABC       |   2000 |   0            |  2000          | 2/18/17 11:28 AM
ABC       |   5110 |  200           |  5310          | 2/20/17 4:52 PM
ABC       |   3066 |   0            |  3066          | 2/18/17 12:48 PM
ABC       |   3069 |   0            |  3069          | 2/21/17 7:38 PM
XYZ       |   2050 |   0            |  2050          | 2/18/17 2:23 PM
XYZ       |   2050 |   0            |  2050          | 2/18/17 3:00 PM
XYZ       |   2044 |   0            |  2044          | 2/18/17 12:34 PM
XYZ       |   5125 |   0            |  5125          | 2/18/17 8:39 PM

对于上述结果,我只需要每个用户名的前2条记录

1 个答案:

答案 0 :(得分:1)

如果使用SQL Server,请使用以下命令添加row_number并进行过滤:

SELECT * FROM (
SELECT  
    bt.FromID, 
    bt.ToID, 
    u.Username, 
    bt.Amount, 
    bt.ToOpeningBal, 
    bt.ToClosingBal, 
    bt.CreatedDate AS TransferDate, 
    u.CreatedDate AS RETLCreatedDate,
    ROW_NUMBER() OVER(PARTITION BY u.Username ORDER BY bt.CreatedDate) rowNum
FROM   BalanceTransfer AS bt 
   INNER JOIN Users AS u ON bt.ToID = u.ID
WHERE u.CreatedDate BETWEEN '2017-01-04 00:00:14.1400000' AND '2017-01-10 00:00:14.1400000'
    AND (bt.ToOpeningbal = 0 or bt.ToOpeningbal = 200)
ORDER BY bt.CreatedDate) a
WHERE rowNum <=2