Sorting multiple columns

Asked

Viewed 48 times

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 order according to the last movement. But the sale will have filled more than one field.
There will be call date, scheduling date and cancellation date for example, the last thing that happened was the cancellation.

I tried so but unsuccessfully:

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

But order it through the first field, ignoring the rest. Any suggestions ?

  • Try to use a max(data_*) to consider only the most recent date of each record

  • 1

    @Andersoncarloswoss he has to use the Greatest clause in reality. I just don’t know if it supports more than 2 columns

  • These date fields are all filled and some are NULL or Blank ?

  • @Robertovalentim Yes, some other null filled

1 answer

2


You can use the clause 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 highest (maximum-value) argument.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.