用于分配平均值的SQL命令

用于分配平均值的SQL命令,sql,sql-server,sql-server-2014,Sql,Sql Server,Sql Server 2014,我需要了解如何在sql中实现这一点。使用SQLServerManagementStudio 我有一个大表,其中包含以下数据: Store Month Value ------ -------- ------- A JAN 1000 A FEB 2400 A MAR

我需要了解如何在sql中实现这一点。使用SQLServerManagementStudio 我有一个大表,其中包含以下数据:

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的值是将1月31日的总天数除以1000

1000/31=32.25

在接下来的几个月里我都要这么做


有人知道我该怎么做吗?我累坏了。我尝试使用excel手动执行此操作,但数据太多且存储不同

因此,您需要查找月份的天数,并使用该天数除以每天的值。如果您不想要日期的实际范围,而只想要月+平均每天,那么第一个查询应该可以工作,最后一个查询中包含完整的日期范围

请注意,我使用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)

显示结果。

这些答案可能包含继续操作所需的信息。SQL Server的哪个版本?如果2012-使用Value/EOMONTH'2014-'+Month+'-01'呃,我使用的SQL server 2014 express版本太多了!我明白了