使用group by的SQL Server查询引发错误

时间:2017-10-03 20:02:34

标签: sql-server tsql

我正在尝试使用计算列和GROUP BY执行以下查询,但由于某种原因它无法正常工作。

SELECT Alquileres.Matricula, SUM(CostoTotal) AS TotalRecaudado, 
       Vehiculos.Marca, Vehiculos.Modelo 
FROM Alquileres INNER JOIN Vehiculos ON Alquileres.Matricula = Vehiculos.Matricula 
GROUP BY Alquileres.Matricula

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

SELECT Vehiculos.Marca, Vehiculos.Modelo, Alquileres.Matricula, SUM(CostoTotal) AS TotalRecaudado
FROM Alquileres 
INNER JOIN Vehiculos 
ON Alquileres.Matricula = Vehiculos.Matricula 
GROUP BY Alquileres.Matricula,Vehiculos.Marca, Vehiculos.Modelo 

按查询选择分组中的所有字段应该是一个字段或一个分组字段。

答案 1 :(得分:-1)

您的查询应如下所示

SELECT 
    Alquileres.Matricula, 
    SUM(CostoTotal) AS TotalRecaudado, 
    Vehiculos.Marca, 
    Vehiculos.Modelo 
FROM 
    Alquileres INNER JOIN 
    Vehiculos 
    ON Alquileres.Matricula = Vehiculos.Matricula 
    GROUP BY 
    Alquileres.Matricula,
    Vehiculos.Marca, -- add this line
    Vehiculos.Modelo -- and this line to group by