sql - Get the most recent record of with unique fields -


i have table in database, , build query return records date contained in last 7 days, number maximum , records group foo_id. example:

+---------------------------------------------------+ | id | number |            date            | foo_id | +---------------------------------------------------+ |   0|     29 | 2013-10-01 08:52:00.000000 |      7 | |   1|     12 | 2013-10-02 08:52:00.000000 |      7 | |   2|     23 | 2013-10-02 08:52:00.000000 |      2 | |   3|     42 | 2013-10-02 08:52:00.000000 |      2 | +---------------------------------------------------+ 

the query returns:

|   3|     42 | 2013-10-02 08:52:00.000000 |      2 | |   0|     29 | 2013-10-01 08:52:00.000000 |      7 | 

i have build query, doesn't work @ all:

calendar time = calendar.getinstance(); time.add(calendar.date, -7);  querybuilder<greattable, integer> qbt = dao.querybuilder(); qbt.where().ge(greattable.date_column_name, time.gettime()); qbt.orderby(greattable.date_column_name, false).orderby(greattable.number_column_name, false); qbt.groupby(greattable.foo_id_column_name); 

and output is:

|   1|     12 | 2013-10-02 08:52:00.000000 |      7 | |   2|     23 | 2013-10-02 08:52:00.000000 |      2 | 

each group foo_id must record maximum number , date.

finally query looks like:

qbt.where().ge(greattable.date_column_name, time.gettime()); qbt.groupby(greattable.foo_id_column_name).having("max(" + greattable.date_column_name + ")"); qbt.orderby(greattable.date_column_name, true); 

pd: when date added there little difference, example 2013-10-02 08:52:00.000000 , 2013-10-02 08:52:00.000010 trick order date too.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -