gpt4 book ai didi

sql - sql语法有什么问题

转载 作者:行者123 更新时间:2023-12-03 08:03:02 25 4
gpt4 key购买 nike

SELECT 
a.Name, a.About,
COUNT(b.Id) AS TotalCities,
SUM(b.NoOfDwellers) AS TotalCityDwellers
FROM
Countries a
LEFT JOIN
Cities b ON a.Id = b.CountryId
WHERE
a.Name LIKE '%some str%'
GROUP BY
a.Id
ORDER BY
a.Name ASC

此SQL返回错误:

Msg 8120, Level 16, State 1, Line 1
Column 'Countries.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

最佳答案

如果您有一个带有SELECT子句的GROUP BY,则SELECT列列表中的每一列都必须是聚合(SUMCOUNTMAX等),否则它必须位于GROUP BY子句中。

您的a.Name列表中同时包含a.AboutSELECT,它们没有由聚合处理-因此,这两列必须出现在GROUP BY子句中

SELECT 
a.Name, a.About,
COUNT(b.Id) AS TotalCities,
SUM(b.NoOfDwellers) AS TotalCityDwellers
FROM
Countries a
LEFT JOIN
Cities b ON a.Id = b.CountryId
WHERE
a.Name LIKE '%some str%'
GROUP BY
a.Id, a.About, a.Name
ORDER BY
a.Name ASC

关于sql - sql语法有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34650126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com