Question

How can I get latest time from two columns eg I have two column name start_time_a and start_time_b both stores value like 2014-05-13 12:34:34 but i need to get latest time from the two columns using Python Django. I am new to django query please help me to get rid of this issue.

Example table:

+-----+-----------------------+-----------------------+ 
|  id |    start_time_a       |    start_time_b       |
+-----+-----------------------+-----------------------+
|  1  |  2014-05-13 12:34:34  |  2014-05-13 12:41:34  |
|  2  |  2014-05-13 12:40:34  |  2014-05-13 12:40:40  |
|  3  |  2014-05-13 12:20:34  |  2014-05-13 12:46:34  | 
+-----+-----------------------+-----------------------+

and i want this output

|  3  |  2014-05-13 12:20:34  |  2014-05-13 12:46:34  | 

because it has latest start_time_b from all timestamps

Was it helpful?

Solution

Referring to the SQL you posted, you can place that into a Django extra() Queryset modifier:

qs = YourModel.objects.extra(select={
    'max_time': '''
    select * from t where (
        start_time_a in (
            select greatest(max(start_time_a), max(start_time_b)) from t
        ) or start_time_b in (
            select greatest(max(start_time_a), max(start_time_b)) from t
        )
    )'''
})

# each YourModel object in the queryset will have an extra attribute, max_time
for obj in qs:
    print obj.max_time

OTHER TIPS

For getting row of greatest value from two column I found this answer and it is quite usefull

select * from t where (
                      start_time_a in (select greatest(max(start_time_a), max(start_time_b)) from t) or
                      start_time_b in (select greatest(max(start_time_a), max(start_time_b)) from t)
                      );

mysql greatest() function

MySQL solution:

If you want to identify latest dates from all records, irrespective of other column values, you can use MAX function on the date columns.

Example:

select max( start_time_a ) as mx_start_time_a
       , max( start_time_b ) as mx_start_time_b
from table_name
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top