日期:2014-05-18  浏览次数:20396 次

一张表查询,只取每个cust_id的前三条记录,求解!
Id cust_id call_date call_result
1 1 2012-03-15 09:00:00 fail
2 1 2012-03-15 09:05:00 number error
3 1 2012-03-15 09:10:00 fail
4 1 2012-03-15 09:15:00 success
5 2 2012-03-15 09:01:00 fail
6 2 2012-03-15 09:06:00 number error
7 2 2012-03-15 09:17:00 fail
8 2 2012-03-15 09:18:00 success
9 3 2012-03-15 09:04:00 fail
10 3 2012-03-15 09:09:00 number error
11 3 2012-03-15 09:19:00 fail
12 3 2012-03-15 09:22:22 success
13 4 2012-03-15 09:07:00 fail
14 4 2012-03-15 09:21:40 success

------解决方案--------------------
SQL code

--> 测试数据:[tbl]
if object_id('[tbl]') is not null drop table [tbl]
create table [tbl]([Id] int,[cust_id] int,[call_date] datetime,[call_result] varchar(7),[C5] varchar(5))
insert [tbl]
select 1,1,'2012-03-15 09:00:00','fail',null union all
select 2,1,'2012-03-15 09:05:00','number','error' union all
select 3,1,'2012-03-15 09:10:00','fail',null union all
select 4,1,'2012-03-15 09:15:00','success',null union all
select 5,2,'2012-03-15 09:01:00','fail',null union all
select 6,2,'2012-03-15 09:06:00','number','error' union all
select 7,2,'2012-03-15 09:17:00','fail',null union all
select 8,2,'2012-03-15 09:18:00','success',null union all
select 9,3,'2012-03-15 09:04:00','fail',null union all
select 10,3,'2012-03-15 09:09:00','number','error' union all
select 11,3,'2012-03-15 09:19:00','fail',null union all
select 12,3,'2012-03-15 09:22:22','success',null union all
select 13,4,'2012-03-15 09:07:00','fail',null union all
select 14,4,'2012-03-15 09:21:40','success',null

select [Id] ,[cust_id],[call_date] ,[call_result] from(
select ROW_NUMBER()OVER(partition by [cust_id] 
order by [call_date] desc) as num,* from tbl)a where num<=3

/*
Id    cust_id    call_date    call_result
4    1    2012-03-15 09:15:00.000    success
3    1    2012-03-15 09:10:00.000    fail
2    1    2012-03-15 09:05:00.000    number
8    2    2012-03-15 09:18:00.000    success
7    2    2012-03-15 09:17:00.000    fail
6    2    2012-03-15 09:06:00.000    number
12    3    2012-03-15 09:22:22.000    success
11    3    2012-03-15 09:19:00.000    fail
10    3    2012-03-15 09:09:00.000    number
14    4    2012-03-15 09:21:40.000    success
13    4    2012-03-15 09:07:00.000    fail
*/

按时间取每个cus_id的前三