2016-09-28 84 views
-1

我有這樣的SQL查詢,我試圖通過多種方式來組織,但它並沒有爲我工作,我想按noExp我如何分組這個SQL查詢?

select Alumnos.nombreComp as Nombre, 
     Carreras.nombre as Carrera, 
     Alumnos.noExp as Expediente, 
     Historial.fecha as Fecha, 
     Historial.equipo as Equipo 
from Alumnos, Historial, Carreras 
where YEAR(fecha)= @año 
    and MONTH (fecha)[email protected] 
    and Historial.noExp = Alumnos.noExp 
    and Alumnos.carrera = Carreras.id_carrera 
    and Alumnos.activo = 1 

幫助!

+0

'我想通過noExp'進行分組,您好,您想對其他列做什麼? – Lamak

+0

顯示相應的值 –

+0

但是,您正在對一列進行分組,其餘的「相應」值是什麼?最小?最大?什麼? – Lamak

回答

0

因此,對於SQL Server,您必須按照您在查詢的select子句中提到的每一列進行分組。 SQL Server需要知道如何組織所有的列。如果您想通過noExp進行分組,然後將其列爲第一個分組選項,然後按照您的數據需要顯示的順序列出分組中的後續列,將獲得主要由noExp分組的列表。

select 
Alumnos.nombreComp as Nombre, 
Carreras.nombre as Carrera, 
Alumnos.noExp as Expediente, 
Historial.fecha as Fecha, Historial.equipo as Equipo 

from Alumnos, Historial, Carreras 
where YEAR(fecha)= @año 
and MONTH (fecha)[email protected] 
and Historial.noExp = Alumnos.noExp 
and Alumnos.carrera = Carreras.id_carrera 
and Alumnos.activo = 1 
GROUP BY Alumnos.noExp, Alumnos.nombrecomp,Carreras.nombre,Historial.fecha 
2
  1. 你真的應該使用正確的聯接語法INNER JOIN爲表和OUTER JOIN之間獲得比賽拿到那裏有一個匹配的比賽,但仍然得到記錄,即使沒有從一個側面匹配。
  2. 要使用GROUP BY,您需要Aggregate Function,目前您沒有任何關於您想要在數據中看到什麼類型的聚合的提示,因此添加一個聚合是沒有意義的。如果你想通過組只有一個字段不是使用MAX關鍵字如下編寫查詢

Sql代碼與正確的聯接語法

SELECT Alumnos.nombreComp as Nombre 
    , Carreras.nombre as Carrera 
    , Alumnos.noExp as Expediente 
    , Historial.fecha as Fecha 
    , Historial.equipo as Equipo 
FROM Alumnos INNER JOIN Historial ON Historial.noExp = Alumnos.noExp 
    INNER JOIN Carreras ON Alumnos.carrera = Carreras.id_carrera 
WHERE YEAR(fecha)= @año 
    AND MONTH (fecha)[email protected] 
    AND Alumnos.activo = 1 
0

select MAX(Alumnos.nombreComp) as Nombre, 
MAX(Carreras.nombre) as Carrera, 
Alumnos.noExp as Expediente, 
Max(Historial.fecha) as Fecha, 
Max(Historial.equipo) as Equipo 
from Alumnos, Historial, Carreras 
where YEAR(fecha)= @año and MONTH (fecha)[email protected] 
and Historial.noExp = Alumnos.noExp 
and Alumnos.carrera = Carreras.id_carrera 
and Alumnos.activo = 1 
GROUP By Alumnos.noExp 
0

使用GROUP BY子句,你應該在一個像平均查詢的一些聚合函數()。使用現場爲您希望通過子句中使用組的聚合功能。