【问题标题】:SQL server - Using Avg() function in where clauseSQL 服务器 - 在 where 子句中使用 Avg() 函数
【发布时间】:2020-01-09 13:35:04
【问题描述】:

我正在做一个反馈工作,我想获取过去 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

如何在上述查询中包含平均条件

当我尝试使用下面的查询在我的选择查询中获得他们的平均 5 星评级时,我在平均列中获得了 DriverId。 从 tblTripfeedback 中选择 DriverId,Count(DriverId) 作为 TotalStars,avg(DriverId) 作为平均值 其中 Rating = 5 和 TripDate >= GetDate() - 30 按 DriverId 分组 有 Count(DriverId) > 10

Ex - ID 为 123 的司机在过去 30 天内完成了 20 次行程,他从客户那里获得了 15 次 5 星评级,这意味着 50% 的 5 星评级,并且他还满足了至少 10 次行程的其他条件。这意味着他有资格获得奖励,因为他获得了超过 25% 的 5 星评级以及至少 10 次旅行

【问题讨论】:

  • Edit 问题并添加一个minimal reproducible example,即架构为CREATE TABLE 语句,示例数据为INSERT INTO 语句以及该示例数据作为表格文本的所需结果。跨度>

标签: sql-server average


【解决方案1】:

WHERE子句中的条件Rating = 5去掉,这样查询就可以返回上个月的所有行,用条件聚合来获取结果:

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

【讨论】:

  • 这很好用,但唯一的问题是当驱动程序具有所有 5 星评级时,平均值显示为 100.0 ,如果至少有 1 个非 5 星评级,则平均值显示为 0.0.. . 平均列中的结果是 100.0 或 0.0
  • Having 子句有问题,它抛出错误 invalid column name 'TotalStars' 和 'Average5Stars'
  • 是 SQL Server 不允许在 having 子句中使用派生列。请参阅我编辑的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-10
  • 2014-03-12
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
相关资源
最近更新 更多