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

SQL SELECT查询中NUMERIC(5,2)在avg函数处的正确放置位置

解答

正确放置位置

NUMERIC(5,2)是数值精度定义,需要和类型转换函数配合,包裹整个avg()窗口函数的计算结果,核心写法如下:

CAST(avg(c.price) over (partition by b.name) AS NUMERIC(5,2)) as average_price

完整修正后的查询语句

你原SQL存在冗余逻辑:使用窗口函数计算分组平均值时不需要额外加GROUP BY和DISTINCT,修正后语句如下:

select 
    b.name, 
    CAST(avg(c.price) over (partition by b.name) AS NUMERIC(5,2)) as average_price
from     
    Catalog a 
join 
    books b on a.book_id = b.id
join 
    movies c on a.movie_id = c.id
where    
    c.price is not null 
    and a.record >= 2

如果你确实需要保留原有GROUP BY逻辑,只需要替换average_price对应的计算部分即可。

补充说明

部分数据库支持其他写法,比如SQL Server也可以用CONVERT(NUMERIC(5,2), avg(c.price) over (partition by b.name))实现相同效果,CAST作为SQL标准语法兼容性最好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 18:06:11