Pergunta

I have a table called "dati" with the column "anni" (primary key) that represents the years from 1960 to 2012 (all the years are consecutives), the column "governi" represents the REFERENCE to the table "governi" and the column "pil" are the values I want to exctract with the values inside the column "presidenti" in the table "governi". If i try to extract min/max value for all years it works. But in this case i need to extract this values in a restricted range of years (for example from 1980 to 1990). And the problem is that doesn't return any max/min value. Table "dati" and table "governi" are connected between column "governo" and column "cod" as you can see in the database schema.

This is the database structure:

TABLE dati:
    anno INT(4),
    governo VARCHAR(6),
    pil FLOAT(10)
TABLE governi:
    cod VARCHAR(6),
    presidente varchar (50)

This is the SQL:

query1:

SELECT a.presidente, b.anno, b.$dato
FROM governi AS a
INNER JOIN dati AS b ON a.cod=b.governo
WHERE b.$dato =(
    SELECT MAX(c.$dato) AS maxpil
    FROM dati AS c
) AND b.anno BETWEEN $inizio AND $fine;

query2:

SELECT a.presidente, b.anno, b.$dato
FROM governi AS a
INNER JOIN dati AS b ON a.cod=b.governo
WHERE b.$dato = (
    SELECT MIN(NULLIF(c.$dato,0)) AS valore
    FROM dati AS c
) AND b.anno BETWEEN $inizio AND $fine;

How can i fix this problem?

Foi útil?

Solução

Try this

SELECT a.presidente, b.anno, b.$dato
FROM governi AS a
INNER JOIN dati AS b ON a.cod=b.governo
WHERE b.$dato =(
    SELECT MAX($dato) AS maxpil
    FROM dati,governi WHERE anno BETWEEN $inizio AND $fine AND governi.cod=dati.govern
) 

SQL Fiddle

Outras dicas

Try this query:

SELECT a.presidente, b.anno, q.valore, q.maxpil
FROM governi AS a
INNER JOIN dati AS b ON a.cod=b.governo
JOIN (
    SELECT MAX(anno) AS maxpil,
           MIN(anno) AS valore
    FROM dati AS c
    WHERE c.anno BETWEEN 
             1965    -- $inizio 
          AND 
             2012    -- $fine
) AS q
ON b.anno BETWEEN q.valore AND q.maxpil

Demo --> http://www.sqlfiddle.com/#!2/480e9/14

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top