就是说要根据客户的产品来显示
比如 有100个会员会员的产品数量都不一样有的可能20个产品,现在要不管一个会员有多少产品,只显示最新的3条在这里
如果某个客户不足3条的话就把那个客户的数据都显示比如
会员 产品 时间
id product date
1 苹果 1999-1-1
1 西瓜 1999-1-2
1 凤梨 1999-9-9
1 菠萝 2008-5-5
1 橘子 1998-8-4
2 电脑 2002-1-1
2 U盘 2003-5-7
2 MP3 2008-2-2
2 手机 2006-7-9
3 车子 2005-7-9
比如 有100个会员会员的产品数量都不一样有的可能20个产品,现在要不管一个会员有多少产品,只显示最新的3条在这里
如果某个客户不足3条的话就把那个客户的数据都显示比如
会员 产品 时间
id product date
1 苹果 1999-1-1
1 西瓜 1999-1-2
1 凤梨 1999-9-9
1 菠萝 2008-5-5
1 橘子 1998-8-4
2 电脑 2002-1-1
2 U盘 2003-5-7
2 MP3 2008-2-2
2 手机 2006-7-9
3 车子 2005-7-9
select * from T a
where (select count(*) from T where id=a.id and product<=a.product)<=3
select * from T a
where (select count(*) from T where id=a.id and [date]>=a.[date]) <=3
--2005
declare @tb table([会员] nvarchar(2),[产品] nvarchar(7),[时间] nvarchar(8))
Insert @tb
select N'1',N'苹果',N'1999-1-1' union all
select N'1',N'西瓜',N'1999-1-2' union all
select N'1',N'凤梨',N'1999-9-9' union all
select N'1',N'菠萝',N'2008-5-5' union all
select N'1',N'橘子',N'1998-8-4' union all
select N'2',N'电脑',N'2002-1-1' union all
select N'2',N'U盘',N'2003-5-7' union all
select N'2',N'MP3',N'2008-2-2' union all
select N'2',N'手机',N'2006-7-9' union all
select N'3',N'车子',N'2005-7-9'
select * from (
Select row_number() over (partition by [会员] order by [会员] ) as id ,* from @tb
) t
where t.id <=3
/*
id 会员 产品 时间
-------------------- ---- ------- --------
1 1 苹果 1999-1-1
2 1 西瓜 1999-1-2
3 1 凤梨 1999-9-9
1 2 电脑 2002-1-1
2 2 U盘 2003-5-7
3 2 MP3 2008-2-2
1 3 车子 2005-7-9
*/
select top 3 时间 from tb where id=a.id order by 时间 desc
) order by a.id,a.date
where exists
(select 1 from (select top 3 * from test where id=a.id order by [date] desc) b
where a.id=b.id and a.product=b.product and a.[date]=b.[date])
--2000
select px = identity(int,1,1) , * into # from @tb
select * from # t
where (select count(1) from # where px<=t.px and [会员] =t.[会员])<=3
/*
px 会员 产品 时间
----------- ---- ------- --------
1 1 苹果 1999-1-1
2 1 西瓜 1999-1-2
3 1 凤梨 1999-9-9
6 2 电脑 2002-1-1
7 2 U盘 2003-5-7
8 2 MP3 2008-2-2
10 3 车子 2005-7-9
*/
Insert @tb
select N'1',N'苹果',N'1999-1-1' union all
select N'1',N'西瓜',N'1999-1-2' union all
select N'1',N'凤梨',N'1999-9-9' union all
select N'1',N'菠萝',N'2008-5-5' union all
select N'1',N'橘子',N'1998-8-4' union all
select N'2',N'电脑',N'2002-1-1' union all
select N'2',N'U盘',N'2003-5-7' union all
select N'2',N'MP3',N'2008-2-2' union all
select N'2',N'手机',N'2006-7-9' union all
select N'3',N'车子',N'2005-7-9' union all
select N'3',N'楼主',N'2005-7-7'
select * from @tb as a
where checksum(会员,产品,时间)
in(select top 3 checksum(会员,产品,时间) from @tb where a.会员=会员 order by 时间 desc)
order by 会员,时间 desc,产品/*
--------------------
1 菠萝 2008-5-5
1 凤梨 1999-9-9
1 西瓜 1999-1-2
2 MP3 2008-2-2
2 手机 2006-7-9
2 U盘 2003-5-7
3 车子 2005-7-9
3 楼主 2005-7-7
*/
where (select count(*) from T where id=a.id and [date]>=a.[date]) <=3
select * from # t
where (select count(1) from # where px<=t.px and [ID] =t.[ID])<=3