x
login about faq Site discussion (meta-askssc)

complicate ordering

DECLARE @table TABLE(col1 VARCHAR(1), col2 INT) INSERT INTO @table SELECT 'C', 5 UNION SELECT 'S', 4 UNION SELECT 'T', 1 UNION SELECT 'W', 2 UNION SELECT 'W', 3

SELECT * FROM @table

HOW TO GENERATE FOLLOWING OUTPUT, WITH CORRECT ORDERING T 1 W 2 S 4 C 5

more ▼

asked Feb 23 '10 at 06:13 PM in Default

DarkCloud gravatar image

DarkCloud
1 1 1

T1
W2
S4
C5

Feb 23 '10 at 06:15 PM DarkCloud
(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first
DECLARE @table TABLE(col1 VARCHAR(1), col2 INT)             
            
INSERT INTO @table             
SELECT 'C', 5 UNION             
SELECT 'S', 4 UNION             
SELECT 'T', 1 UNION             
SELECT 'W', 2 UNION             
SELECT 'W', 3            
            
SELECT  col1, col2 = min(col2)            
FROM    @table            
group by col1            
order by col2            
            
select  col1, col2            
from    (            
        select  col1, col2, row_no = row_number() over (partition by col1 order by col2)            
        from    @table            
    ) t            
where   t.row_no    = 1            
order by col2            
more ▼

answered Feb 23 '10 at 08:33 PM

Squirrel 1 gravatar image

Squirrel 1
1.6k 1 3

(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments



Facebook logo Follow Ask SSC on Facebook
Find Ask SSC on Google+
linkedin logo Find us on LinkedIn

Topics:

x1835
x12

asked: Feb 23 '10 at 06:13 PM

Seen: 362 times

Last Updated: Feb 23 '10 at 06:13 PM

Copyright © 2002-2012 Simple Talk Publishing. All Rights Reserved. If you have any queries, please contact the site administrators.
Ask SQL Server Central is a community service provided by Red Gate.