各位师兄 我想建个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
字段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
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
*/
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
on a.id=b.id and a.[date]=b.[date]
order by id/*
1 2013-06-26 00:00:00.000
2 2013-01-01 00:00:00.000
3 2012-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 行受影响)
好的 谢谢你 哈哈 我公司领导们自己开发底层的东西 不支持存储过程 现在只能写sql
好的 谢谢你 哈哈 我公司领导们自己开发底层的东西 不支持存储过程 现在只能写sql
可以写在函数里面,就能传参了,
表值函数支持么?
好的 谢谢你 哈哈 我公司领导们自己开发底层的东西 不支持存储过程 现在只能写sql
可以写在函数里面,就能传参了,
表值函数支持么?
貌似只支持view跟table 因为他们会把这些转化为实体类 我们只要写where后面的语句
----查询view 的sql ,select * from view
---查询表值函数的sql,select * from functionName('参数')
我们只需要写('参数') .是会执行成的