DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   MySQL (http://www.daniweb.com/forums/forum126.html)
-   -   Advanced SQL query problem (http://www.daniweb.com/forums/thread162888.html)

joliejoker Dec 18th, 2008 2:35 pm
Advanced SQL query problem
 
Hello.
I'm burning my head on a problem with a query.
Querying a payments table, I need to find the actual membership category (let's say: IDCATEGORIA). If I run this:

SELECT idpersona, idcategoria, datapagamento, datascadenza
FROM personacategoria
WHERE NOW( )
BETWEEN datapagamento
AND datascadenza
ORDER BY idpersona, datascadenza

I get this result:

idPersona  idcategoria  datapagamento  datascadenza
2  2  2008-12-07  2010-03-31
4  2  2007-12-17  2009-03-31
4  1  2008-11-08  2010-03-31
5  2  2008-12-08  2010-03-31
6  2  2007-11-11  2009-03-31
7  2  2008-12-10  2010-03-31

The problem, as you can notice, is the second and third row: person 4 paid on the 2007-12-17 its membership, and then again one year later on the 2008-11-08. So, if I query now (2008-12-17), I obviously am in the overlapping period, so that I retrieve two records.
What I want to do is to retrieve, in cases like this, only the oldest DATASCADENZA record (obviously, for each single IDPERSONA).
I've tried lots of things today, but nothing seems to work... any hint?

thanks,
jj

n.b.: (just in case you need it): primary key for the table is IDPERSONA+IDCATEGORIA+DATAPAGAMENTO

hielo Dec 21st, 2008 2:16 am
Re: Advanced SQL query problem
 
SELECT idpersona, Max(idcategoria) as categoria, Max(datapagamento) as pagamento, Max(datascadenza) as scadenza 
FROM personacategoria 
WHERE NOW( )
BETWEEN datapagamento
AND datascadenza
GROUP BY idpersona
ORDER BY idpersona


All times are GMT -4. The time now is 9:00 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC