我的 CTE 查询未按我的预期工作

问题描述 投票:0回答:1

这是我的询问:

WITH Ase AS 
(
    SELECT CAST(AVG(percent_water AS w) AS DECIMAL(10,2))
    FROM dbo.countries
)
SELECT un_continential_region, un_subregion, Ase
FROM dbo.countries
WHERE percent_water > 0
GROUP BY un_continential_region, un_subregion
ORDER BY Ase DESC;

我遇到的错误是

AVG 不是可识别的内置函数名称

此查询的目标是我想将平均水百分比转换为小数,然后按 un_Continial_region 和 Un_subregion 进行分组。

我哪里出错了?

sql sql-server common-table-expression
1个回答
0
投票

您不需要 CTE,只需在 select 子句中执行所需的计算即可:

SELECT
      un_continential_region
    , un_subregion
    , CAST(AVG(percent_water) AS DECIMAL(10,2)) AS Ase
FROM dbo.countries
WHERE percent_water > 0
GROUP BY
      un_continential_region
    , un_subregion
ORDER BY
      Ase DESC;

另请注意

AVG(percent_water AS w)
无效,“as w”不属于这些括号内。另外,您可能想在求平均值之前将数据强制转换为小数,在这种情况下,请使用:

    , AVG(CAST(percent_water AS DECIMAL(10,2))) AS Ase
© www.soinside.com 2019 - 2024. All rights reserved.