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
12013-06-26 00:00:00.000
22013-01-01 00:00:00.000
32012-12-12 00:00:00.000
*/
on a.id=b.id and a.[date]=b.[date]
order by id
/*
12013-06-26 00:00:00.000
22013-01-01 00:00:00.000
32012-12-12 00:00:00.000
*/
[解决办法]
--建临时表
if object_id('Tempdb..#t') is not null drop table #t
create table #t(
id int identity(1,1) not null,
UserId int null,
LoginTime datetime null
)
--建示例数据
Insert Into #t
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'
--查询日期
declare @time datetime
set @time='2013-07-01 '
--查询
select UserId,max(LoginTime) as LoginTime
from #t
where LoginTime <@time
group by UserId
--结果
(6 行受影响)
UserId LoginTime
----------- -----------------------
1 2013-06-26 00:00:00.000
2 2013-01-01 00:00:00.000
3 2012-12-12 00:00:00.000
(3 行受影响)
表值函数支持么?
[解决办法]
居然会能支持 view ,不支持函数
----查询view 的sql ,select * from view
---查询表值函数的sql,select * from functionName('参数')