GROUP BY 适用于不在 GROUP BY 中的 Select 列

GROUP BY Works with Select columns not in GROUP BY

为什么当 SELECTed 列既不在 GROUP BY 子句中也不在聚合函数中时,这个 GROUP BY 仍然有效。 DATABASE SCHEMA HERE

SELECT FirstName,
   LastName,
   City,
   Email,
   COUNT(I.CustomerId) AS Invoices
FROM Customers C INNER JOIN Invoices I
ON C.CustomerId = I.CustomerId
GROUP BY C.CustomerId

此语法在 SQLite 中是允许的并记录在案:Bare columns in an aggregate query.

FirstNameLastNameCityEmail 列称为 列。

此类列获得 任意 值,但使用 MIN()MAX() 中的一个(且仅此一个)的情况除外。在这种情况下,裸列的值取自包含最小或最大聚合值的行。

在任何情况下使用此语法时都要小心,因为您会得到意想不到的结果。

我想说两件事:

Group by will work if the column name exists in the table you are working on. In your query, you have inner join Customer table with Invoice table. From your schema, I can see in the Invoice table CustomerId column exists.

In SQL serve have to give all the column name that you selected plus your desired column name. What I mean by that your query should be like this.

 SELECT FirstName,
   LastName,
   City,
   Email,
   COUNT(I.CustomerId) AS Invoices
FROM Customers C INNER JOIN Invoices I
ON C.CustomerId = I.CustomerId
GROUP BY C.CustomerId, 
         LastName,
         City,
         Email
  

所以,我认为您正在使用 MySQL 这就是它起作用的原因。