Friday, February 24, 2012

How can I use SELECT DISTINCT and maintain the original order

Say I have a result set with two fields numbers and letters.

1 A
3 A
1 B
2 B


The result set is ordered by the letters column. How can I select the distinct numbers from the result set but maintain the current order?

When I try

select distinct Number from MyResultSetit will reorder the new result set by the Number field and return

1
2
3


However, I'd like maintain the Letter order and return

1
3
2

try this

create

table #test(nnint,llchar(1))

insert

into #test

values

(1,'A')

insert

into #test

values

(3,'A')

insert

into #test

values

(1,'B')

insert

into #test

values

(2,'B')

select

nnfrom(select nn,min(ll)llfrom #test

group

by nn

)

aa

order

by ll

drop

table #test

No comments:

Post a Comment