我必须从下面的表格中找到每周平均值(仅限工作日 - 星期一至星期五)。我正在搜索的平均值是AVAI_NUM。我必须计算给定时期内每周AVAI_NUM的平均值。
实施例: 如果期限是2016年1月:
declare @dDateFrom date = cast('2016-01-01' as date)
declare @dDateTo date = cast('2016-01-31' as date)
表格如下:
declare @scavai table
(
avai_key int,
avai_dat date,
avai_num int
)
用数据填写表格:
insert into @scavai(avai_Key, avai_dat, avai_num)
select 1, cast('2016-01-01' as date), 3
union all
select 1, cast('2016-01-02' as date), 2
union all
select 1, cast('2016-01-03' as date), 5
union all
select 1, cast('2016-01-04' as date), 6
union all
select 1, cast('2016-01-05' as date), 1
union all
select 1, cast('2016-01-06' as date), 8
union all
select 1, cast('2016-01-07' as date), 4
union all
select 1, cast('2016-01-08' as date), 3
union all
select 1, cast('2016-01-09' as date), 2
union all
select 1, cast('2016-01-10' as date), 1
union all
select 1, cast('2016-01-11' as date), 9
union all
select 1, cast('2016-01-12' as date), 7
union all
select 1, cast('2016-01-13' as date), 3
union all
select 1, cast('2016-01-14' as date), 8
union all
select 1, cast('2016-01-15' as date), 3
union all
select 1, cast('2016-01-16' as date), 2
union all
select 1, cast('2016-01-17' as date), 3
union all
select 1, cast('2016-01-18' as date), 1
union all
select 1, cast('2016-01-19' as date), 4
union all
select 1, cast('2016-01-20' as date), 5
union all
select 1, cast('2016-01-21' as date), 7
union all
select 1, cast('2016-01-22' as date), 3
union all
select 1, cast('2016-01-23' as date), 3
union all
select 1, cast('2016-01-25' as date), 3
union all
select 1, cast('2016-01-26' as date), 3
我知道如何计算给定时期内的周数:
select DATEDIFF(ww, '2016-01-01', '2016-01-31')
但我不知道如何计算每周工作日的AVAI_NUM,并将其除以特定周的天数,然后总结所有这些并除以周数?
答案 0 :(得分:1)
试,
select *,
AVG(cast(avai_num as decimal)) over
(partition by datepart(week, avai_dat) order by (select 1)) avg1
from @scavai
where avai_dat between @dDateFrom and @dDateTo
order by avai_dat