SQL Server - 显示每个用户的前12条记录

时间:2014-06-06 17:54:07

标签: sql sql-server

我需要为每个用户显示12个第一个结果,我尝试了Top(12)并且它只选择了前12行,然后我做了一些搜索并发现我需要使用聚合函数,这就是我所拥有的:

SELECT id, fname, lnam, Invoice, amnt, [bill period] 
FROM TABLE1
GROUP BY id, fname, lnam, Invoice, amnt, [bill period] 
HAVING --Not really sure!

这是Table1

id  fname   lname   Invoice amnt    bill period
1   John    Doe 480991  38.42   201406
1   John    Doe 481102  38.42   201407
1   John    Doe 481047  38.42   201408
1   John    Doe 485053  38.42   201409
1   John    Doe 489759  38.42   201410
1   John    Doe 489788  38.42   201411
1   John    Doe 489817  38.42   201412
1   John    Doe 489846  38.42   201501
1   John    Doe 489875  38.42   201502
1   John    Doe 489905  38.42   201503
1   John    Doe 489933  38.42   201504
1   John    Doe 489963  38.42   201505
1   John    Doe 490044  38.42   201506
1   John    Doe 490138  38.42   201507
2   Rich    Doe 480992  41.41   201406
2   Rich    Doe 481103  41.41   201407
2   Rich    Doe 481048  41.41   201408
2   Rich    Doe 485057  41.41   201409
2   Rich    Doe 489765  41.41   201410
2   Rich    Doe 489794  41.41   201411
2   Rich    Doe 489823  41.41   201412
2   Rich    Doe 489852  41.41   201501
2   Rich    Doe 489881  41.41   201502
2   Rich    Doe 489911  41.41   201503
2   Rich    Doe 489936  41.41   201504
2   Rich    Doe 489979  41.41   201505
2   Rich    Doe 490066  41.41   201506
2   Rich    Doe 490160  41.41   201507
2   Rich    Doe 490161  41.41   201508

谢谢。

3 个答案:

答案 0 :(得分:2)

----使用解析函数rank()使其返回值的等级 在一组values.With子句中,您将创建一组临时数据。

WITH TEMP AS
(
SELECT id, fname, lnam, Invoice, amnt, bill_period,
rank() OVER (PARTITION BY ID ORDER BY bill_period) AS RK
FROM TABLE1
)
SELECT id, fname, lnam, Invoice, amnt, bill_period FROM TEMP WHERE RK<13;

答案 1 :(得分:1)

您可以使用分析row_number()函数,而不是使用group by子句。假设您根据id列标识用户:

SELECT id, fname, lnam, Invoice, amnt, [bill period]
FROM   (SELECT id, fname, lnam, Invoice, amnt, [bill period], 
        ROW_NUMBER() OVER (PARTITION BY id ORDER BY [bill period] ASC) AS rn 
        FROM TABLE1) t
WHERE  rn <= 12

答案 2 :(得分:0)

SELECT t2.*
FROM (SELECT DISTINCT id FROM TABLE1) t1
CROSS APPLY (SELECT TOP 12 * FROM t1 WHERE id = t1.id ORDER BY bill_period) t2