关于SQL语句的一个问题:

来源:百度知道 编辑:UC知道 时间:2024/06/03 06:57:03
现在有一张表,表中有字段temp1,temp2及其他字段,temp2字段为datetime类型,想要搜索出不同的temp1对应的temp2不同天数的最大值(如:temp2值的日期为2008-10-1这一天具体时间的最大值)的记录,该怎么写SQL语句??
最后结果应该是不同temp1的有记录的那天的最新的那条记录。

多给点分。
答案:

select * from #temp1 a where temp2=(select top 1 temp2 from #temp1 where datediff(d,temp2,a.temp2)=0 and temp1 = a.temp1 order by temp2 desc)

-----------------------------------------
测试数据
create table #temp1 (temp1 varchar(20) null,temp2 datetime null)
insert into #temp1 values('QW','2008-1-2 12:01')
insert into #temp1 values('QW','2008-1-2 16:01')
insert into #temp1 values('QW','2008-1-2 13:01')
insert into #temp1 values('Qs','2008-1-2 12:01')
insert into #temp1 values('QW','2008-1-1 12:01')

select * from #temp1 a where temp2=(select top 1 temp2 from #temp1 where datediff(d,temp2,a.temp2)=0 and temp1 = a.temp1 order by temp2 desc)

drop table #temp1

结果集:-----------------------
QW 2008-01-02 16:01:00.000
Qs 2008-01-02 12:01:00.000
QW 2008-01-01 12:01:00.000