如何获取这个表中某个时间段的max(),min(),avg(),还有就是排序中的最后一个值,也就是当前值
求助下
如何获取这个表中某个时间段的max(),min(),avg(),还有就是排序中的最后一个值,也就是当前值
字段A相当于一个类型 有很多重复字段
我现在是这个样子的
select Max(B) as BB, Min(B) as CC, Avg(B) as DD, FF=getdate(),A as AA from dd_test
where F>='2013/8/13 16:34:40' and F<'2013/8/13 18:34:40' group by A
最难的是没办法查询出
排序中的最后一个值,也就是当前值
[解决办法]
select TA.*,dd_test.b
from (
select Max(c) as MaxC,....from dd_test
where F>='2013/8/13 16:34:40' and F<'2013/8/13 18:34:40' group by A) TA,
dd_test
where dd_test.c=TA.MaxC
[解决办法]
if OBJECT_ID('tempdb..#temp', 'u') is not null drop table #temp;
CREATE TABLE #TEMP(A VARCHAR(10), B INT, C DATETIME)
insert #temp
select 'ttt','2','2013-08-07 08:05:05' union all
select 'ttt','3','2013-08-07 08:06:05' union all
select 'ttt','4','2013-08-07 08:07:05' union all
select 'fff','5','2013-08-07 08:05:05' union all
select 'fff','9','2013-08-07 08:06:05' union all
select 'fff','15','2013-08-07 08:07:05'
SELECT M.*, 当前值=Y.b, 时间=y.C
FROM
(
SELECT a,
CAST(AVG(1.*B) AS FLOAT) AS 平均值 ,
MAX(B) AS 最大值 ,
MIN(B) AS 最小值
FROM #TEMP
WHERE C >= '2013-08-07 08:05:05'
AND C < '2013-08-08 08:07:05'
GROUP BY A
) m
CROSS APPLY
(
SELECT TOP(1) *
FROM #TEMP N
WHERE N.A = M.A
ORDER BY c DESC
) Y
/*
a平均值最大值最小值当前值时间
fff9.666666155152013-08-07 08:07:05.000
ttt34242013-08-07 08:07:05.000
*/