十大和十分之一的平均值bottom float_value,包含日期,按日期分组

时间:2012-07-18 19:46:05

标签: sql sql-server-2005 average common-table-expression

我有一张这样的表:

| prodID  | date     |  perm
---------------------------------   
|200      |8/7/2011  | 81.742 
|200      |8/7/2011  | 81.644
|200      |8/7/2011  | 81.302
|200      |8/7/2011  | 81.057
|201      |8/7/2011  | 80.932
|201      |8/7/2011  | 80.839
|201      |8/7/2011  | 80.622
|201      |8/7/2011  | 80.557
|201      |8/7/2011  | 80.541

(除了有点大) 发生的事情的细分:我想取前十个值(和底部10个值)的平均值,其中prodid = somevalue在这种情况下为200.

代码:

declare @myid int
set @myid = 200

;with high as  --top ten average
(
 select prodid, CONVERT(CHAR(10),  DATEADD(DAY, AVG(DATEDIFF(DAY, 0, CONVERT    
(SMALLDATETIME, [date]))), 0),     101) as date, max(perm)as max_perm, avg(perm) 
as   
high_perm from   
( select prodid, date, perm, 
 row_number() over(partition by date order by perm desc) as nt    
 from live_pilot_plant
 where prodid = @myid) as T 
 where nt <= 10
 group by prodid
),
low as   -- bottom ten average
(
select prodid, CONVERT(CHAR(10),  DATEADD(DAY, AVG(DATEDIFF(DAY, 0, CONVERT    
(SMALLDATETIME, [date]))), 0),101) as date, min(perm) as min_perm, avg(perm) 
as low_perm  from   
( select prodid, date, perm,  
  row_number() over(partition by date order by perm asc) as nt    
  from live_pilot_plant
  where prodid = @myid) as T 
  where nt <= 10
  group by prodid
)

select l.prodid, l.date, l.low_perm as low_avg, m.high_perm as high_avg,
(m.high_perm -    l.low_perm) as delta
from low l
left outer join high m
on l.prodid = m.prodid 

产生类似这样的东西:

|  prodID  |   date     |  low_avg   |  high_avg  |  delta   |
|   200    | 08/07/2011 |   68.752   |  79.1976   |  10.444  |

这些数字不准确 -

这是好事和花花公子 - 除了不是很好的。我的意思是有很多prodID,并且根据prodID做一个这太慢了。如何根据日期获取low_avg和high_avg(按prodID分组)

这样的事情:

| date       | prodID  | low_avg  | high_avg  |  delta  |
| 08/07/2011 | 200     |  60      |  80       |  20     |
| 08/07/2011 | 201     |  70      |  100      | 100     |

注意:您可能已经注意到了一个疯狂的转换日期。原因是一些prodID重叠日期即。 200 2011年8月7日和2011年8月8日,我需要平均日期(这是一个varchar)。因此,如果8/7/2011有100行,然后8/8/2011有9行,则最终查询将生成日期为/ 8/7/2011

1 个答案:

答案 0 :(得分:1)

以下查询同时为所有产品执行此操作:

select lpp.prod_id, lpp.date,
       AVG(case when seqnum_asc <= 10 then perm end) as avg_bottom10,
       AVG(case when seqnum_desc <= 10 then perm end) as avg_top10,
       (AVG(case when seqnum_desc <= 10 then perm end) - AVG(case when seqnum_asc <= 10 then perm end)) as delta
from (select lpp.*,
             ROW_NUMBER() over (partition by prodid, date order by perm) as seqnum_asc,
             ROW_NUMBER() over (partition by prodid, date order by perm desc) as seqnum_desc
      from live_pilot_plan lpp
     ) lpp
group by lpp.prod_id, lpp.ate