x

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, 2010 at 06:13 PM in Default

DarkCloud gravatar image

DarkCloud
1 1 1 1

T1
W2
S4
C5
Feb 23, 2010 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, 2010 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.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

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

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x1951
x22

asked: Feb 23, 2010 at 06:13 PM

Seen: 721 times

Last Updated: Feb 23, 2010 at 06:13 PM