sql server 查找帅选后每个人的第一条记录
各位师兄 我想建个view 但不知道怎么写sql 麻烦你们指点下 大恩不言谢
字段1 字段2
2 2013-08-01
2 2013-01-01
2 2012-05-01
1 2013-06-26
1 2013-02-01
3 2012-12-12
我要可以根据日期筛选出每个人的第一条数据
比如我输入日期 2013-07-01 结果是
2 2013-01-01
1 2013-06-26
3 2012-12-12
------解决方案--------------------没看懂,请问输入日期2013-07-01与结果有什么关系?
------解决方案--------------------select a.*
from tb a
inner join (select id,max([date]) as [date] from tb group by id)b
on a.id=b.id and a.[date]=b.[date]
------解决方案--------------------
create table test(字段1 int ,字段2 datetime)
insert into test values (2,'2013-08-01')
insert into test values (2,'2013-01-01')
insert into test values (2,'2012-05-01')
insert into test values (1,'2013-06-26')
insert into test values (1,'2013-02-01')
insert into test values (3,'2012-12-12')
select 字段1,字段2=CONVERT(varchar, MAX(字段2), 120 )
from test
where 字段2<'2013-07-01'
group by 字段1
/*
字段1 字段2
1 2013-06-26 00:00:00.000
2 2013-01-01 00:00:00.000
3 2012-12-12 00:00:00.000
*/
------解决方案--------------------create table #tb(id int,[date] datetime)
insert into #tb
select 2,'2013-08-01'
union all select 2,'2013-01-01'
union all select 2,'2012-05-01'
union all select 1,'2013-06-26'
union all select 1,'2013-02-01'
union all select 3,'2012-12-12'
select a.*
from #tb a
inner join (select id,max([date]) as [date] from #tb where [date]<'2013-07-01' group by id)b