假设我有一个索引视图,该视图记录给定月份人们在酒店停留的天数。创建报表时,我想在结果集中插入一行,显示所有月份的平均天数。
我的索引视图是这样的:
NumMonth | NumPeople | NumDays
1 | 4 | 3
1 | 4 | 4
2 | 1 | 9
3 | 3 | 6
3 | 2 | 10
如何选择单行的平均停留时间?
我当前的查询看起来像这样:
INSERT INTO @results(month1, month2, month3, quarter1)
SELECT
'month1' = ISNULL(CASE WHEN v.NumMonth = 1
THEN convert(decimal(10,3), sum(v.NumPeople * v.NumDays)) / convert(decimal(10,3), sum(v.NumPeople))
ELSE null END, 0),
'month2' = ISNULL(CASE WHEN v.NumMonth = 2
THEN convert(decimal(10,3), sum(v.NumPeople * v.NumDays)) / convert(decimal(10,3), sum(v.NumPeople))
ELSE null END, 0),
'month3' = ISNULL(CASE WHEN v.NumMonth = 3
THEN convert(decimal(10,3), sum(v.NumPeople * v.NumDays)) / convert(decimal(10,3), sum(v.NumPeople))
ELSE null END, 0),
'quarter1' = ISNULL(CASE WHEN v.NumMonth = 1 OR v.NumMonth = 2 OR v.NumMonth = 3
THEN convert(decimal(10,3), sum(v.NumPeople * v.NumDays)) / convert(decimal(10,3), sum(v.NumPeople))
ELSE null END, 0)
FROM MonthTotalsView v with(noexpand)
我得到选择列表无效的错误,因为我的NumMonth没有聚合或分组。但我希望全部写在一行里,而不是按月分。如有任何帮助,我将不胜感激。
我要找的结果如下:
month1 | month2 | month3 | quarter1
2.5 | 9 | 7.6 | 5.357
如何选择单行的平均停留时间?
假设您的数据代表每次入住一行:
select avg(numdays)
from MonthTotalsView;
如果你想按月收费:
select nummonth, avg(numdays)
from MonthTotalsView
group by nummonth;