使用sql server一个月平均10天

时间:2015-03-02 20:24:05

标签: sql sql-server

过去两年我每天都有一堆价值观。我需要获得该月10天的平均值。与9月1日至9月10日,9月11日至20日等的平均值一样......

值在事实表中,我的目标是从中创建聚合事实表。事实表中的字段是 - 位置键,时间键和值。

time_dim表格包含日历日期和time_key

有任何建议怎么做?

感谢您的帮助。

阿伦

示例数据

Location_Key----Time_Key----Value
2345------------414---------300
333-------------413---------400
1---------------2346--------566
14--------------1987--------900
2379------------111---------250
346-------------110---------1125
188-------------333---------567
187-------------422---------333
21--------------789---------170
211-------------2-----------900

时间暗淡的日历日期类似于2013.01.012013.01.022013.01.03 .....等。 我需要获得平均10天的平均值。

附加了time_dim中的示例数据

TIME_KEY    CAL_DATE    DAY_OF_MONTH    WEEK_NUMBER MONTH_NUMBER    WEEK    DEKADE  DEKADE_NUMBER   MONTH   YEAR_MONTH  JULIAN  YEAR    DEKADE_KEY  MONTH_DESC
413 2013.01.01  1   1   1   2013W00 2013D01 1   Jan 2013M01 1   2013    2628    2013M01
103 2013.01.02  2   1   1   2013W00 2013D01 1   Jan 2013M01 2   2013    2628    2013M01
683 2013.01.03  3   1   1   2013W00 2013D01 1   Jan 2013M01 3   2013    2628    2013M01
414 2013.01.04  4   1   1   2013W00 2013D01 1   Jan 2013M01 4   2013    2628    2013M01
207 2013.01.05  5   1   1   2013W00 2013D01 1   Jan 2013M01 5   2013    2628    2013M01
684 2013.01.06  6   1   1   2013W00 2013D01 1   Jan 2013M01 6   2013    2628    2013M01
415 2013.01.07  7   2   1   2013W01 2013D01 1   Jan 2013M01 7   2013    2628    2013M01
6   2013.01.08  8   2   1   2013W01 2013D01 1   Jan 2013M01 8   2013    2628    2013M01
685 2013.01.09  9   2   1   2013W01 2013D01 1   Jan 2013M01 9   2013    2628    2013M01
416 2013.01.10  10  2   1   2013W01 2013D01 1   Jan 2013M01 10  2013    2628    2013M01
686 2013.01.11  11  2   1   2013W01 2013D02 2   Jan 2013M01 11  2013    2629    2013M01
208 2013.01.12  12  2   1   2013W01 2013D02 2   Jan 2013M01 12  2013    2629    2013M01
687 2013.01.13  13  2   1   2013W01 2013D02 2   Jan 2013M01 13  2013    2629    2013M01
417 2013.01.14  14  3   1   2013W02 2013D02 2   Jan 2013M01 14  2013    2629    2013M01
104 2013.01.15  15  3   1   2013W02 2013D02 2   Jan 2013M01 15  2013    2629    2013M01

SQL查询

select  min(cal_date), max(cal_date), sum(daily_weather), location_key, dekade_key
from 
(select t.*,(row_number() over (order by cal_date) -
              row_number() over (partition by daily_weather order by cal_date)
             ) as grpid
      from aggr_fact_testing t
     ) t
group by grpid, cal_date,location_key,dekade_key

1 个答案:

答案 0 :(得分:1)

怎么样......

SELECT t.Location_Key, td.MONTH_NUMBER, td.YEAR, CASE WHEN (td.DAY_OF_MONTH <= 10) THEN '1-10' ELSE CASE WHEN (td.DAY_OF_MONTH <= 20) THEN '11-20' ELSE '21-31' END END, AVG(t.Value) 
FROM yourTable t
INNER JOIN time_dim td ON td.TIME_KEY = t.Time_key
GROUP BY t.Location_Key, td.MONTH_NUMBER, td.YEAR, CASE WHEN (td.DAY_OF_MONTH <= 10) THEN '1-10' ELSE CASE WHEN (td.DAY_OF_MONTH <= 20) THEN '11-20' ELSE '21-31' END END

Haven没有对它进行过测试,因为我不确定这是不是你正在寻找的东西。看看并发表评论。