Sorting multiple columns

3

The sales table has the following structure:

id_venda | nome_cliente | data_venda | data_agendamento | data_cancelamento | data_ligacao

Where the "date" fields are all datetime. I would like to sort according to the last move that occurred. But the sale will have filled more than one field. It will have a date of call, date of appointment and date of cancellation for example, the last thing that happened was the cancellation.

I tried this way but without success:

 select * from vendas order by data_venda desc, data_agendamento desc,
 data_cancelamento desc, data_ligacao desc;

But sort by the first field, ignoring the rest. Any suggestions?

    
asked by anonymous 19.11.2018 / 20:32

1 answer

2

You can use the GREATEST :

SELECT *
  FROM vendas
 ORDER BY GREATEST(data_venda, data_agendamento, data_cancelamento, data_ligacao);
  

GREATEST ()

     

With two or more arguments, returns the largest (maximum-valued) argument.

Or in free translation:

  

With two or more arguments, returns the largest (maximum-value) argument.

    
19.11.2018 / 20:39