SQL 服务器 - 在 where 子句中使用 Avg() 函数
SQL server - Using Avg() function in where clause
我正在做一项反馈工作,我想获取过去 30 天内获得客户 5 星评级的司机名单,他们的总行程中应该有 25% 的平均 5 星评级在过去 30 天内至少获得 10 5 星评级
使用下面的查询,我可以获得在过去 30 天内获得超过 10 个 5 星评级的司机,但我需要检查他们的总行程中应该有平均 25% 的 5 星评级。
Select DriverId, Count(DriverId) as TotalStars from tblTripfeedback
where Rating = 5 and TripDate >= GetDate() - 30
group by DriverId
Having Count(DriverId) > 10
如何在上述查询中包含平均条件
当我尝试使用下面的查询在我的 select 查询中获得他们的平均 5 星评级时,我在平均列中得到了 DriverId。
Select DriverId,Count(DriverId) 作为 TotalStars,avg(DriverId) 作为来自 tblTripfeedback 的平均值
其中 Rating = 5 且 TripDate >= GetDate() - 30
按 DriverId 分组
有 Count(DriverId) > 10
Ex - Driver ID 123 在过去 30 天内完成了 20 次行程,他从客户那里获得了 15 次 5 星评级,这意味着 50 % 5 星评级,并且他还满足了另一个最低条件10 次旅行.. 这意味着他有资格获得奖励,因为他获得了超过 25% 的 5 星评级并且至少有 10 次旅行
从WHERE
子句中移除条件Rating = 5
,以便查询returns上个月的所有行并使用它来获得条件聚合的结果:
select DriverId,
count(case when Rating = 5 then DriverId end) as TotalStars,
100.0 * avg(case when Rating = 5 then 1.0 else 0 end) as Average5Stars
from tblTripfeedback
where TripDate >= GetDate() - 30
group by DriverId
having
count(case when Rating = 5 then DriverId end) > 10
and
100.0 * avg(case when Rating = 5 then 1.0 else 0 end) > 25
我正在做一项反馈工作,我想获取过去 30 天内获得客户 5 星评级的司机名单,他们的总行程中应该有 25% 的平均 5 星评级在过去 30 天内至少获得 10 5 星评级
使用下面的查询,我可以获得在过去 30 天内获得超过 10 个 5 星评级的司机,但我需要检查他们的总行程中应该有平均 25% 的 5 星评级。
Select DriverId, Count(DriverId) as TotalStars from tblTripfeedback
where Rating = 5 and TripDate >= GetDate() - 30
group by DriverId
Having Count(DriverId) > 10
如何在上述查询中包含平均条件
当我尝试使用下面的查询在我的 select 查询中获得他们的平均 5 星评级时,我在平均列中得到了 DriverId。 Select DriverId,Count(DriverId) 作为 TotalStars,avg(DriverId) 作为来自 tblTripfeedback 的平均值 其中 Rating = 5 且 TripDate >= GetDate() - 30 按 DriverId 分组 有 Count(DriverId) > 10
Ex - Driver ID 123 在过去 30 天内完成了 20 次行程,他从客户那里获得了 15 次 5 星评级,这意味着 50 % 5 星评级,并且他还满足了另一个最低条件10 次旅行.. 这意味着他有资格获得奖励,因为他获得了超过 25% 的 5 星评级并且至少有 10 次旅行
从WHERE
子句中移除条件Rating = 5
,以便查询returns上个月的所有行并使用它来获得条件聚合的结果:
select DriverId,
count(case when Rating = 5 then DriverId end) as TotalStars,
100.0 * avg(case when Rating = 5 then 1.0 else 0 end) as Average5Stars
from tblTripfeedback
where TripDate >= GetDate() - 30
group by DriverId
having
count(case when Rating = 5 then DriverId end) > 10
and
100.0 * avg(case when Rating = 5 then 1.0 else 0 end) > 25