如何获得平均年初至今

时间:2016-08-02 01:53:59

标签: sql-server

表格如下。

Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
25  20  45  10  15  23  23  17  19  21  24  33

我希望显示上个月的平均值。意思是,如果这是八月,我想展示到七月。如果当前月份是9月,我想要到7月份。该表应如下所示。

Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Avg
25  20  45  10  15  23  23  17  19  21  24  33  23

2 个答案:

答案 0 :(得分:2)

您的数据格式非常差。您可以更好地使用列中的数据。但是,你可以这样做一个痛苦的查询:

select ((case when month(getdate()) > 1 then jan else 0 end) +
        (case when month(getdate()) > 2 then feb else 0 end) +
        . . .
        (case when month(getdate()) > 11 then nov else 0 end)
       ) /
       ((case when month(getdate()) > 1 then 1 else 0 end) +
        (case when month(getdate()) > 2 then 1 else 0 end) +
        . . .
        (case when month(getdate()) > 11 then 1 else 0 end)
       )

答案 1 :(得分:1)

你想要这样的东西吗?:

SELECT * INTO tbl_Month_AVG
FROM (VALUES
(25,1),(20,2),(45,3),(10,4),(15,5),(23,6),(23,7),(17,8),(19,9),(21,10),(24,11),(33,12)) as a(Num,Mon)

;WITH Avg_On as (
SELECT Mon, SUM(Num) OVER(ORDER BY Mon)
    / COUNT(*) OVER(ORDER BY (SELECT NULL)) as Avg_On
FROM tbl_Month_AVG
WHERE Mon < 8
)
SELECT Avg_On FROM Avg_On
WHERE Mon = (Select MAX(Mon) FROM Avg_On)