我需要根据SSRS图表的历史数据计算平均值:
此查询返回每个月的平均值:
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
当我添加以下WHERE子句时,我得到March(2个月前)的平均值:
WHERE month = MONTH(GETDATE())-2
AND year = YEAR(GETDATE())
现在的问题是我想要从6个月前检索数据; MONTH(GETDATE()) - 6
将输出-1而不是12.我也有一个问题,即年份变为2016年,我对如何在查询中实现逻辑有点不确定。
我想我可能会发生这种错误...有什么建议吗?
答案 0 :(得分:2)
在进行比较之前,使用DATEADD函数减去日期之后的月份。例如:
WHERE SnapshotDate BETWEEN DATEADD(month, -6, GETDATE()) AND GETDATE()
答案 1 :(得分:1)
MONTH(GETDATE())返回一个int,因此您可以转到0或负值。你需要一个管理这个的用户标量函数,当< = 0
时添加12