我从过去的3、6和10个月中获得不同月份的平均值。
select SUM(GrossAmount)/10 as Averageten
FROM Table
WHERE CreatedDate >= DATEADD(MONTH, -10, GETDATE())
select SUM(GrossAmount)/6 as Averagesix
FROM Table
WHERE CreatedDate >= DATEADD(MONTH, -6, GETDATE())
select SUM(GrossAmount)/3 as Averagethree
FROM Table
WHERE CreatedDate >= DATEADD(MONTH, -3, GETDATE())
例如,我得到三个不同的值:
1200.22
2300.22
4500
我想获得这三个值的平均值
(1200.22 + 2300.22 + 4500) / 3
如何从这些单独的查询中添加值。
答案 0 :(得分:3)
使用并集合并三个查询,然后取平均值
select avg(Averageten)
from
(select SUM(GrossAmount)/10 as Averageten
FROM Table
WHERE CreatedDate >= DATEADD(MONTH, -10, GETDATE())
union
select SUM(GrossAmount)/6
FROM Table
WHERE CreatedDate >= DATEADD(MONTH, -6, GETDATE())
union
select SUM(GrossAmount)/3
FROM Table
WHERE CreatedDate >= DATEADD(MONTH, -3, GETDATE())
)a
或者,您可以使用条件聚合来查找值,因为您是从具有不同条件的同一张表中查询的
select ((sum(case when CreatedDate >= DATEADD(MONTH, -10, GETDATE()) then GrossAmount end)/10)
+(sum(case when CreatedDate >= DATEADD(MONTH, -6, GETDATE()) then GrossAmount end)/6)
+(sum(case when CreatedDate >= DATEADD(MONTH, -3, GETDATE()) then GrossAmount end)/3))/3
from tablename
答案 1 :(得分:3)
使用条件聚合。
SELECT
(
SUM(CASE WHEN CreatedDate >= DATEADD(MONTH, -10, GETDATE()) THEN GrossAmount END) / 10 +
SUM(CASE WHEN CreatedDate >= DATEADD(MONTH, -6, GETDATE()) THEN GrossAmount END) / 6 +
SUM(CASE WHEN CreatedDate >= DATEADD(MONTH, -3, GETDATE()) THEN GrossAmount END) / 3
) / 3 AS [10, 6, 3 Average]
FROM Table
WHERE CreatedDate >= DATEADD(MONTH, -10, GETDATE()) -- this covers all three cases