我只是想做一个Count(汽车每个客户)
所以我尝试这样:
SELECT tbl_Clients.FirstName, tbl_Clients.LastName, tbl_Clients.Phone,
COUNT(*) AS VehiculeTotal
FROM tbl_Contrat
INNER JOIN tbl_Clients ON tbl_Contrat.Client = tbl_Clients.ID
GROUP BY tbl_Contrat.Client
和简单的方法:
SELECT FirstName, LastName, Phone, COUNT(*) AS VehiculeTotal
FROM tbl_Clients, tbl_Contrat GROUP BY Client
但看起来我遇到了同样的问题:
Column 'tbl_Clients.FirstName'(LastName and phone too) is invalid in the
select list because it is not contained in
either an aggregate function or the GROUP BY clause.
但不想按他们分组
我需要显示FirstName,LastName和Phone!
请帮助
答案 0 :(得分:0)
当您按结果使用组时,根据您分组的列将其分区为唯一组。在您的情况下,tbl_client.id应该是唯一的,因此如果组中使用的任何其他列都不是唯一的,则无关紧要。假设您有两个名为John Doe的客户端,其客户端ID为1和2,则分组仍然会根据ID将它们分开,并且不会再进行分组。
此查询应该执行您想要的操作。我冒昧地为表名使用别名,以使其更短,更易读。
SELECT cli.FirstName, cli.LastName, cli.Phone, COUNT(*) AS VehiculeTotal
FROM tbl_Contrat con
INNER JOIN tbl_Clients cli ON con.Client = cli.ID
GROUP BY cli.id, cli.FirstName, cli.LastName
请注意,通过使用内部联接,您可以消除因某些原因可能没有任何汽车的任何客户,这当然可以,但如果您想要返回不具备任何内容的客户你应该使用左连接的任何车辆,如下所示:
SELECT id, firstname, lastname, COUNT(tbl_Contrat.Client) AS VehiculeTotal
FROM tbl_Clients
LEFT JOIN tbl_Contrat ON tbl_Contrat.Client = tbl_Clients.ID
GROUP BY id, firstname, lastname