2017-03-22 46 views
0

我使用下面的查詢檢索事務,但我只需要前2記錄每個用戶如何取n爲了頂個記錄查詢

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記錄每個用戶名

+0

您正在使用哪個數據庫管理系統? – jarlh

+0

MS SQL Server 2014 – Luqman

+3

google row_number()over(按某種東西排序的分區) – Veljko89

回答

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