Sorting 2 Columns at the same time SQL Server

Asked

Viewed 483 times

0

I have the following table structure.

Ticket | Data | ID

The data field is datetime, ticket, id and generator are int.

What I need is for ticket and date fields to be sorted at the same time.

Current result.

Ticket    Data/Hora     
532       06/06/2018
532       10/08/2017
532       11/07/2018
532       01/03/2016

Expected result.

Ticket    Data/Hora
532       01/03/2016
532       10/08/2017
532       06/06/2018
532       11/07/2018

Current query below.

select  
w.service_req_id Ticket,
CONVERT(VARCHAR(10), w.to_time, 103) + ' ' + CONVERT(VARCHAR(8), w.to_time, 108) [Data/Hora],
'Interna' [Ação é Pública? (Pública/Interna)],
case when u.ref_id = '1' then '454' 
     when u.ref_id is null then ur.ref_id else u.ref_id end as Gerador,
w.description +char(13)+char(10) Descrição,
cast(w.id as varchar(100)) as Seq
from work_report w
left join sysaid_user u on u.user_name = w.user_name
left join service_req se on se.id = w.service_req_id
left join sysaid_user ur on ur.user_name = se.responsibility
where w.service_req_id in(532)
and (w.description not in('') and w.description not in ('.'))
order by 1,6

Note that I tried order by for ticket and id, but failed.

1 answer

1


You just need to use the ORDER BY according to the priority:

ORDER BY w.service_req_id, w.to_time

SELECT - Clause ORDER BY

Sorts data returned by a query on SQL Server. Use this clause to:

  • Classify the result set of a query by the specified column list and optionally limit the returned rows to a specified range. The order in which lines are returned in a result set is not guaranteed unless a clause ORDER BY is specified.
  • Determine the order in which the values of classification function shall be applied to the set of results.
  • I think it’s safer to order by 1.2

  • @Motta would no longer work because he had ordered the date as a string

  • "Convert" does not convert to DATE ?!

  • @Motta not, in that case is converting to varchar. Aside from that putting the column position in order by is dangerous. If you add a column before breaks the logic

  • The error starts with storing data as a string, starts to complicate queries that should be trivial.

  • @Motta yes but that’s not part of the question

Show 1 more comment

Browser other questions tagged

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