You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL查询求助:计算编辑平均生产力及计算列显示0值

解决AverageProductivity列显示0的问题

你的查询逻辑框架是对的,但结果全为0的核心问题出在SQL的整数除法特性上:当两个整数类型的数值相除时,SQL会自动截断小数部分,只返回整数结果。比如200页的书间隔300天出版,200/300会得到0而非预期的0.67,这就是你看到全0结果的原因。

修正后的查询语句

我们只需要把除法运算中的任意一个操作数转换为浮点类型,就能触发浮点运算,保留小数部分。这里提供两种简洁的实现方式:

方式1:用CAST转换数据类型

select * from (
 select e.EditorName, b.BookName,
 -- 将页数转为DECIMAL类型,避免整数除法
 round( CAST(b.NoOfPages AS DECIMAL(10,2)) / datediff( day, lag(b.DateOfPublication) over(partition by b.EditorID order by b.DateOfPublication), b.DateOfPublication ), 2 ) AverageProductivity
 from book b
 inner join editor e on e.EditorID = b.EditorID
) x
where AverageProductivity is not null

方式2:用1.0触发浮点运算(更简洁)

select * from (
 select e.EditorName, b.BookName,
 -- 用1.0乘以页数,自动转换为浮点类型
 round( 1.0 * b.NoOfPages / datediff( day, lag(b.DateOfPublication) over(partition by b.EditorID order by b.DateOfPublication), b.DateOfPublication ), 2 ) AverageProductivity
 from book b
 inner join editor e on e.EditorID = b.EditorID
) x
where AverageProductivity is not null

额外说明

  • 你的原查询已经通过LAG()函数和外层WHERE子句正确排除了编辑的第一本书(第一本书的LAG()结果为NULL,对应的AverageProductivity也为NULL,会被过滤)。
  • 如果存在两本书同一天出版的情况,datediff会返回0,导致除以0错误,建议添加额外的过滤条件(比如datediff(...) > 0)来规避这种情况。

内容的提问来源于stack exchange,提问作者YHapticY

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:22:19