riad
riad

Reputation: 7194

SQL: need to sort the value using group by or any other way

This is the example scenery of my table. First I have to find, order by ITime asc, BUT if there have any record those are same in ITime then the record order will be “pass->fail->withdraw”. Please check the below temporary table.

if object_id('tempdb.dbo.#temp321','U') is not null
drop table tempdb.dbo.#temp321
create table #temp321(
id int,
uname varchar(50),
ITime datetime,
Result varchar(10)
)
INSERT into #temp321 values('1','a','2012-11-12 13:12:28.103','pass')
INSERT into #temp321 values('2','b','2012-11-12 13:12:28.103','fail')
INSERT into #temp321 values('3','c','2012-11-12 12:58:30.000','pass')
INSERT into #temp321 values('4','d','2012-11-12 13:12:28.103','withdrow')
INSERT into #temp321 values('5','e','2012-11-12 12:58:41.360','withdraw')
INSERT into #temp321 values('6','f','2012-11-12 13:12:28.103','pass')
INSERT into #temp321 values('7','g','2012-11-12 13:12:28.103','fail')
select ID from #temp321 ORDER BY ITime ASC
drop table #temp321


Expected outcomes ID value : 3,5,1,6,2,7,4

How i do it? thanks in advance.

Upvotes: 3

Views: 105

Answers (1)

RichardTheKiwi
RichardTheKiwi

Reputation: 107696

ORDER BY ITIME ASC,
         CASE Result WHEN 'pass' THEN 1
                     WHEN 'fail' THEN 2
                     WHEN 'withdraw' THEN 3
                     ELSE 4
                     END,
         ID;

Upvotes: 5

Related Questions