DellaeMme
DellaeMme

Reputation: 73

SQL query on the same table with join and group by

I've a problem with this query:

SELECT source.cod,source.nome,source.ruolo,SUM(source.giocato),ROUND(SUM(source.fvoto)/SUM(source.giocato),2) as media,ROUND(SUM(source.voto)/SUM(source.giocato),2),SUM(source.gs),SUM(source.ass),SUM(source.amm),SUM(source.esp),SUM(source.rigsub),SUM(source.rigpar),source.stagione,parent.stagione,parent.cod,parent.squadra,parent.valore,parent.esiste,parent.gg
FROM db_dati source
WHERE source.ruolo=".$q." AND source.stagione=".$stagione."
GROUP BY source.cod,source.politico,source.stagione
HAVING source.politico=0
JOIN db_dati parent
ON source.stagione=parent.stagione AND source.cod=parent.cod
ORDER BY media DESC

but it always respond me:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'JOIN db_dati parent ON source.stagione=parent.stagione AND source.cod=parent.cod' at line 1

Upvotes: 0

Views: 1903

Answers (2)

Strawberry
Strawberry

Reputation: 33935

There's some redundant stuff in there...

 SELECT source.cod
      , source.nome
      , source.ruolo
      , SUM(source.giocato)
      , ROUND(SUM(source.fvoto)/SUM(source.giocato),2) media
      , ROUND(SUM(source.voto)/SUM(source.giocato),2)
      , SUM(source.gs)
      , SUM(source.ass)
      , SUM(source.amm)
      , SUM(source.esp)
      , SUM(source.rigsub)
      , SUM(source.rigpar)
      , source.stagione
      , parent.stagione
      , parent.cod
      , parent.squadra
      , parent.valore
      , parent.esiste
      , parent.gg
   FROM db_dati source
   JOIN db_dati parent
     ON parent.stagione = source.stagione 
    AND parent.cod = source.cod
  WHERE source.ruolo = ".$q." 
    AND source.stagione=".$stagione."
    AND source.politico=0
  GROUP 
     BY source.cod
  ORDER BY media DESC

Upvotes: 0

Himanshu
Himanshu

Reputation: 32602

You need to join tables before WHERE clause:

SELECT source.cod,source.nome,source.ruolo,SUM(source.giocato),ROUND(SUM(source.fvoto)/SUM(source.giocato),2) as media,ROUND(SUM(source.voto)/SUM(source.giocato),2),SUM(source.gs),SUM(source.ass),SUM(source.amm),SUM(source.esp),SUM(source.rigsub),SUM(source.rigpar),source.stagione,parent.stagione,parent.cod,parent.squadra,parent.valore,parent.esiste,parent.gg
FROM db_dati source
JOIN db_dati parent
ON source.stagione=parent.stagione AND source.cod=parent.cod
WHERE source.ruolo=".$q." AND source.stagione=".$stagione."
GROUP BY source.cod,source.politico,source.stagione
HAVING source.politico=0
ORDER BY media DESC

Upvotes: 2

Related Questions