SQL计数子集的平均值

时间:2016-09-30 22:47:39

标签: sql sql-server tsql average resultset

我们假设我有一个索引视图,这个视图会影响人们在某个月内入住酒店的天数。创建报告时,我想在结果集中插入一行,显示所有月份的平均天数。

我的索引视图如下所示:

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

1 个答案:

答案 0 :(得分:0)

  

如何在一行中选择平均逗留时间?

假设您的数据代表每次入住一行:

select avg(numdays)
from MonthTotalsView;

如果你想每月这样:

select nummonth, avg(numdays)
from MonthTotalsView
group by nummonth;