SQL Server中具有日期平均值的新列

时间:2015-05-18 17:18:31

标签: sql sql-server average

我有这张桌子:

OrganizationCode | CreatedDate              | TotalCost
102              |  2015-05-18 00:00:00.000 | 200
102              |  2015-05-18 00:00:00.000 | 550
102              |  2015-05-15 00:00:00.000 | 700
102              |  2015-05-15 00:00:00.000 | 1200
103              |  2015-01-27 00:01:12.720 | 1275,46
103              |  2015-01-27 00:01:12.720 | 1275,46 
103              |  2015-01-27 00:01:12.720 | 1275,46

我需要添加两列:

每日平均值=按日期列出的值总和

每日金额=按日期的金额

我想要下面的结果:

OrganizationCode | CreatedDate      | TotalCost | Daily Average | Daily Amount    
-----------------|------------------|-----------|---------------|--------    
102              | 2015-05-18 00:00 | 200       | 375           |  2    
102              | 2015-05-18 00:00 | 550       | 375           |  2    
102              | 2015-05-15 00:00 | 700       | 950           |  2    
102              | 2015-05-15 00:00 | 1200      | 950           |  2    
103              | 2015-01-27 00:01 | 1275,46   | 1275,46       |  3    
103              | 2015-01-27 00:01 | 1275,46   | 1275,46       |  3    
103              | 2015-01-27 00:01 | 1275,46   | 1275,46       |  3

我尝试这个查询:

   SELECT OrganizationCode 
          , CreatedDate 
          , (SELECT avg(TotalCost) AS x
                 FROM #TempLocalOrg
                 Group By CAST(CreatedDate as date)) 
   FROM #TempLocalOrg 

没有成功,子选择有效,但我需要复制结果

2 个答案:

答案 0 :(得分:3)

执行此操作的最佳方法是使用窗口函数:

SELECT OrganizationCode, CreatedDate
     , AVG(TotalCost) OVER ( PARTITION BY CreatedDate ) AS [Daily Average]
     , COUNT(*) OVER ( PARTITION BY CreatedDate ) AS [Daily Amount]
  FROM #TempLocalOrg;

以上假设日期已四舍五入或截断为最接近的日期。

答案 1 :(得分:0)

SELECT OrganizationCode 
      , CreatedDate 
      , TotalCost
      , aggregates.AvgCost AS 'Daily Average '
      , aggregates.CountCost AS 'Daily Amount'
FROM #TempLocalOrg tmp
CROSS APPLY
(
   SELECT AVG(TotalCost) as AvgCost
         ,COUNT(1) AS CountCost
   FROM #TempLocalOrg crossTemp
   WHERE CAST(tmp.CreatedDate as date) = CAST(crossTemp.CreatedDate as date)
) aggregates

由于您不需要聚合这些值,我们无法使用group by。 相反,我使用CROSS APPLY匹配每一行的日期并汇总它的结果,以便将其应用于每一行不同的行。 如果您需要任何澄清,请随时与我联系。