-1

我有多个 ctes。在我的选择语句中,我必须根据条件过滤值。这是我的查询。

SELECT roadName
    ,sum(roadLength) AS sumRoadLength
    ,avg(elevationDifference) AS eglAvgDepth
    ,avg(elevationDifference) AS pglAvgDepth
    ,
FROM cte3
GROUP BY roadName
ORDER BY roadName

在“elevationDifference”下,有很多从 -10 到 +20 的值,它们通过“roadName”传播。我想要完成的是,如果所有“elevationDifference”值都<0并取平均值,则“eglAvgDepth”将返回。与 pglAvgDepth 相同的情况,其中值 > 0。

我尝试添加 where 语句,但仅适用于 eglAvgDepth

WHERE elevationDifference < 0
GROUP BY roadName
ORDER BY roadName
4

1 回答 1

1

只需添加一个条件表达式:

avg(case when elevationDifference < 0 then elevationDifference end) as eglAvgDepth,
avg(case when elevationDifference > 0 then elevationDifference end) as pglAvgDepth,

编辑:

您已经表达了这一点,即您想要基于所有值是正值还是负值的值。如果是这样:

(case when max(elevationDifference) < 0 then avg(elevationDifference) end) as eglAvgDepth,
(case when max(elevationDifference) > 0 then avg(elevationDifference) end) as pglAvgDepth,
于 2020-02-11T11:53:42.400 回答