sql 语法有什么问题
What is the wrong with the sql syntax
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
这个SQLreturns错误:
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.
如果您有一个带有 GROUP BY
子句的 SELECT
,则 SELECT
列列表中的每一列都必须 一个聚合(SUM
、COUNT
、MAX
等),或者它必须在 GROUP BY
子句中。
您的 SELECT
列表中的 a.Name
和 a.About
均未由聚合处理 - 因此,这两列必须出现在 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
在包含 group by
子句的查询中,结果中的每一行都代表整组行,这些行共享它们作为分组依据的列的相同值。因此,您 select 的每个项目都必须是这些列之一、对它们的 row-based 操作或聚合函数。您似乎在尝试根据 a
的 name
和 about
来汇总 b
的值。如果这是真的,您应该相应地修改您的 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 IS NULL
GROUP BY
a.Name, a.About -- here!
ORDER BY
a.Name ASC
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
这个SQLreturns错误:
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.
如果您有一个带有 GROUP BY
子句的 SELECT
,则 SELECT
列列表中的每一列都必须 一个聚合(SUM
、COUNT
、MAX
等),或者它必须在 GROUP BY
子句中。
您的 SELECT
列表中的 a.Name
和 a.About
均未由聚合处理 - 因此,这两列必须出现在 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
在包含 group by
子句的查询中,结果中的每一行都代表整组行,这些行共享它们作为分组依据的列的相同值。因此,您 select 的每个项目都必须是这些列之一、对它们的 row-based 操作或聚合函数。您似乎在尝试根据 a
的 name
和 about
来汇总 b
的值。如果这是真的,您应该相应地修改您的 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 IS NULL
GROUP BY
a.Name, a.About -- here!
ORDER BY
a.Name ASC