2014-09-23 28 views
2

我需要了解如何在sql中执行此操作。使用SQL Server Management Studio中 我有诸如用于分配平均值的SQL命令

Store   Month    Value 
------   --------   ------- 
    A    JAN    1000 
    A    FEB    2400 
    A    MAR    2310 
    A    APR    1409 
    A    MAY    1500 
    A    JUN    1000 
    A    JUL    2400 
    A    AUG    2310 
    A    SEP    1409 
    A    OCT    1500 
    A    NOV    1409 
    A    DEC    1500 

我上面的数据数据的大表,但我希望有按日期当月的平均值。例如

Store   Month    Value 
------   --------   ------- 
    A   1/1/2014    32.25 
    A   2/1/2014    32.25 
    A   3/1/2014    32.25 
    A   4/1/2014    32.25 
    .    .     . 
    .    .     . 
    .    .     . 
    .    .     . 
    A   31/1/2014    32.25 

其中的32.25值从除以一月为1000的值的总天数(31)衍生...

三十一分之一千= 32.25

而余下的几个月我都要这样做。

任何人都知道我该怎么做?我完全被困住了。我尝试使用Excel手动执行操作,但数据太多且店铺太多

+0

http://dba.stackexchange.com/questions/18626/how-to-get-the-total-days-per-month-between-two-dates这些答案可能包含您需要进行的信息。 – 2014-09-23 10:42:46

+0

哪个版本的SQL Server?如果2012年 - 使用价值/ EOMONTH('2014-'+月+'-01') – 2014-09-23 10:48:22

+0

呃我使用SQL Server 2014快递版本 – user3436187 2014-09-24 01:15:32

回答

1

因此,您希望查找月份中的天数,并使用该天数来划分每天的价值。如果你不想要实际的日期范围,但只是月+平均值。每天,那么第一个查询应该工作,完整的日期范围包含在最后一个查询中。

请注意,我使用2014年作为年,所以如果你想运行闰年的查询,你必须做相应的调整。

对于SQL Server 2012+:(使用新的EOMONTH函数)

select 
    store, month, value, 
    cast(value as decimal(10,2))/datepart(day,eomonth(cast('2014-' + month + '-01' as date))) as val_per_day 
from table1 

对于SQL Server < 2012:如果你想在天太,你可以(使用日期函数)

select 
    store, month, value, 
    cast(value as decimal(10,2))/datepart(day, 
    cast(dateadd(month, datediff(month, 0, cast('2014-' + month + '-01' as date))+1, 0)-1 as date)) as val_per_day 
from table1 

使用公用表表达式来生成一年中所有日子的表格并将其用于左连接:

;With cte(d) as 
(
    select cast('2014-01-01' as date) as d 
     union all 
    select dateadd(day, 1, d) 
     from cte 
     where d < '2014-12-31' 
) 

select *, 
    cast(Value as decimal(10,2))/ 
    -- for pre 2012 
    datepart(day,cast(dateadd(month, datediff(month, 0, cast('2014-' + month + '-01' as date))+1, 0)-1 as date)) as val_per_day 
    --day(EOMONTH(d)) -- for 2012 
from cte c 
left join table1 t on t.month = left(datename(month, d),3) 
option (MaxRecursion 1000) 

Sample SQL Fiddle显示结果。

+0

非常感谢!我已经知道了 – user3436187 2014-09-24 01:47:53