SQL Server / SSRS:根据分组和历史值计算月平均值

时间:2017-05-10 13:01:32

标签: sql sql-server reporting-services

我需要根据SSRS图表的历史数据计算平均值:

  • 本月
  • 上个月
  • 2个月前
  • 6个月前

此查询返回每个月的平均值:

SELECT 
    avg_val1, month, year
FROM
    (SELECT 
         (sum_val1 / count) as avg_val1, month, year
     FROM
         (SELECT 
              SUM(val1) AS sum_val1, SUM(count) AS count, month, year
          FROM
              (SELECT 
                   COUNT(val1) AS count, SUM(val1) AS val1, 
                   MONTH([SnapshotDate]) AS month, 
                   YEAR([SnapshotDate]) AS year
               FROM 
                   [DC].[dbo].[KPI_Values]
               WHERE 
                   [SnapshotKey] = 'Some text here'
                   AND No = '001'
                   AND Channel = '999'
               GROUP BY 
                   [SnapshotDate]) AS sub3
          GROUP BY 
              month, year, count) AS sub2
     GROUP BY sum_val1, count, month, year) AS sub1
ORDER BY 
    year, month ASC

enter image description here

当我添加以下WHERE子句时,我得到March(2个月前)的平均值:

WHERE month = MONTH(GETDATE())-2
  AND year = YEAR(GETDATE())

enter image description here

现在的问题是我想要从6个月前检索数据; MONTH(GETDATE()) - 6将输出-1而不是12.我也有一个问题,即年份变为2016年,我对如何在查询中实现逻辑有点不确定。

我想我可能会发生这种错误...有什么建议吗?

2 个答案:

答案 0 :(得分:2)

在进行比较之前,使用DATEADD函数减去日期之后的月份。例如:

WHERE SnapshotDate BETWEEN DATEADD(month, -6, GETDATE()) AND GETDATE()

答案 1 :(得分:1)

MONTH(GETDATE())返回一个int,因此您可以转到0或负值。你需要一个管理这个的用户标量函数,当< = 0

时添加12