0

我创建了一个有多个列的视图。我需要从外部表中检索一些数据。 在此处输入图像描述 在此处输入图像描述

cte4 as (
SELECT *,
case 
    when roadName=roadNameUserData then sec1
else 'x' 
end as roadCrossSection1

FROM dbo.roadSectionAndPavementUserData,cte3
    )

--"roadName" is from cte computed column view
--"roadNameUserData" is from other table("dbo.roadSectionAndPavementUserData") where records are to be extracted
--sec1 is the column in table "dbo.roadSectionAndPavementUserData" where the results coming from 



-----final view
SELECT roadName,
sum(roadLength) as sumRoadLength,roadCrossSection1


FROM cte4 
group by roadName
order by roadName

当我执行查询时,出现以下错误

“列 'cte4.roadCrossSection1' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。”

在此处输入图像描述

这是添加额外的 groupby 语句后的结果。正确的记录是 sumRoadLength 的较小值。

4

3 回答 3

1

roadCrossSection1你也需要分组

SELECT roadName, roadCrossSection1,
               sum(roadLength) as sumRoadLength
FROM cte4 
group by roadName, roadCrossSection1
order by roadName, roadCrossSection1

更新

SELECT roadName, sum(roadLength) as sumRoadLength
FROM cte4 
group by roadName 
order by roadName
于 2020-02-15T07:05:45.687 回答
1

从您的评论中:

我观察到正确的结果应该是 roadName 记录中的较小值和那些不为空的值

我认为你需要条件聚合:

SELECT roadName,
  sum(case when roadCrossSection1 is not null then roadLength end) as sumRoadLength,
  max(roadCrossSection1) roadCrossSection1
FROM cte4 
group by roadName
order by roadName
于 2020-02-15T08:01:30.400 回答
0

错误表示如果您希望在 select 子句中使用 roadCrossSection1,您必须在 roadCrossSection1 上应用任何聚合函数,例如 MIN、Max、Sum、Avg,或者您必须将其放在 group by 子句中,因为 roadCrossSection1 可能具有相同道路名称但相同的多个值通过在 roadLength 上调用聚合函数仅评估 roadLength 的一个值的时间

于 2020-02-15T07:34:35.647 回答