declare @tb table (id int identity,dc datetime,da datetime,db decimal(9,1),pa datetime)
insert into @tb (da,dc,db,pa)
select '2009-4-1','2009-4-1',121.5,'2009-4-18'
union
select '2009-4-13','2009-4-13',90.8,'2009-4-17'
/***************************************************************/
select id,da,db,pa,avgdb=round((db/case when datediff(dd,dc,pa)>10 then 10 else datediff(dd,dc,pa) end),2)
from @tb
where db<>0
insert into @tb (id,da,dc,db)
select 11 ,'2009-4-10','2005-1-1',100
union
select 12 ,'2009-4-10','2005-1-13',200
/***************************************************************/
select id,da,(select top 1 db from @tb where da='2009-04-10'),avgdb=round((db/case when datediff(dd,dc,da)>10 then 10 else datediff(dd,dc,da) end),2)
from @tb
where db<>0
wang as (select 井号, 注水时间 ,创建井时间 ,水压 ,
时间差=datediff(dd,创建井时间,@用户结束时间) from tb where 创建井时间 between @用户开始时间 and @用户结束时间)
select 井号, 注水时间 ,创建井时间 ,水压,平均水压=(select avg(水压) from wang where 井号=t.井号 and 时间差<10)
from wang t
select 井号, max(创建井时间) 创建井时间, sum(水压)/(case when count(1)>=10 then 10 else count(1) end) 平均水压
from tb a where datediff(dd,创建井时间, (select max(当天时间) from tb where 井号=a.井号))>=10 and isnull(水压,0)<>0 group by 井号
union all
select 井号,max(创建井时间) 创建井时间, sum(水压)/count(1) 平均水压
from tb a where datediff(dd,创建井时间, (select max(当天时间) from tb where 井号=a.井号))<10 and isnull(水压,0)<>0 group by 井号
--或者干脆这样
select 井号, sum(水压)/(case when count(1)>=10 then 10 else count(1) end) 平均水压
from tb a where datediff(dd,创建井时间, (select max(当天时间) from tb where 井号=a.井号))>=10 and isnull(水压,0)<>0 group by 井号
union all
select 井号, sum(水压)/count(1) 平均水压
from tb a where datediff(dd,创建井时间, (select max(当天时间) from tb where 井号=a.井号))<10 and isnull(水压,0)<>0 group by 井号
--如果记录数>10,按当天时间取后10条记录,那就这样。
--我把语句又重新优化了一下,这样就可以了,包括记录小于10条的。
select 井号,max(注水时间) 最大注水时间,avg(水压) 平均水压,max(当天时间) 最大当天时间 from
(select 井号,注水时间,创建井时间,水压,当天时间 from tb a
where 当天时间 in (select top 10 当天时间 from tb where 井号=a.井号 and isnull(水压,0)<>0 order by 当天时间 desc) and isnull(a.水压,0)<>0 ) b
group by 井号 order by 井号
--如果记录数>10,按当天时间取前10条记录,那就这样。
--我把语句又重新优化了一下,这样就可以了,包括记录小于10条的。
select 井号,max(注水时间) 最大注水时间,avg(水压) 平均水压,max(当天时间) 最大当天时间 from
(select 井号,注水时间,创建井时间,水压,当天时间 from tb a
where 当天时间 in (select top 10 当天时间 from tb where 井号=a.井号 and isnull(水压,0)<>0 order by 当天时间 asc) and isnull(a.水压,0)<>0 ) b
group by 井号 order by 井号