求sql语句或者自定义函数

来源:百度知道 编辑:UC知道 时间:2024/06/24 17:08:11
表名 test
表结构如下
test_time test_value
2009-08-01 00:30:00 100
2009-08-01 01:00:00 110
2009-08-01 01:30:00 120
...... ...
表中的数据为每隔半个小时增加一条记录
现在我先求出上个月那天的test_value和最大,不知道该怎么写,求教高手!谢谢!

上个月是什么意思:针对当前系统时间来说的,如果是这样则如下:
自定义函数:
CREATE FUNCTION dbo.FncDate (@datetime datetime)
RETURNS varchar(10) AS
BEGIN
declare @tmp varchar(10)
if (@datetime is null)
set @tmp= ''
else
set @tmp=cast(year(@datetime) as varchar(4))+'-'+cast(Month(@datetime) as varchar(2))+'-'+cast(day(@datetime) as varchar(2))
return @tmp
END

查询语句:
select max(t.test_value) test_value,t.test_time from
( select count(test_value) test_value,dbo.FncDate(test_time) test_time from test where datediff(m,test_time,getdate())=1 group by dbo.FncDate(test_time) ) t

select max(value) from(
select sum(test_value) value from
(select substring(convert(varchar,test_time),1,10) 日期,test_value from test)t1
where 日期=substring(convert(varchar,dateadd(d,1,test_time)),1,10)
group by 日期) t2;

---
以上,希望对你有所帮助。

select max(value) from 表 where time liek 日期'%'