views:

58

answers:

2

I have a table which looks like

Col1    col2 col3 col4 col5
1  5       1     4     6
1  4       0     3     7   
0  1       5     6     3
1  8       2     1     5
4  3       2     1     4

The script is

declare @t table(col1 int, col2 int, col3 int,col4 int,col5 int)
insert into @t 
select 1,5,1,4,6 union all
select 1,4,0,3,7 union all
select 0,1,5,6,3 union all
select 1,8,2,1,5 union all
select 4,3,2,1,4

I want the output to be every column being sorted in ascending order i.e.

Col1 col2 col3 col4 col5
    0  1       0     1     3
    1  3       1     1     4
    1  4       2     3     5
    1  5       2     4     6
    4  8       5     6     7

How to do it?

Thanks in advance

+3  A: 

That sort order is correct.

It's sorted first by col1, then by col2 (within any duplicates in col1), etc...

Notice how for same value in col2, col2 is in ascending order:

Col1    col2    col3    col4    col5 
1       4         0     3       7 
1       5         1     4       6 
1       8         2     1       5 

Here's another example. Imagine we have a list of Lastname, Firstname:

Smith, Ian
Smith, John
Smith, Dave
Smith, Jane
Green, Jim

Sorted by Lastname ASC, Firstname ASC that would be:

Green, Jim
Smith, Dave
Smith, Ian
Smith, Jane
Smith, John
Mitch Wheat
But I want the output to be sorted for every column
Newbie
The thing you think you want is impossible!! You would have to treat each column as separate from its row.
Mitch Wheat
+3  A: 

Columns are not independent of their row -- sort order applies to the whole row, not to individual columns. All data within a row is understood to be related -- you cannot individually slice/dice/rearrange data that violates this.

You can't do what you want to do in the current structure you have.

Joe
+1. Excellent explanation.
Mitch Wheat
+1 I wouldn't say it's *impossible* to return those results, but it's almost certainly Doing It Wrong(tm) at one or more levels.
Jon Seigel
Sir, then what will be the query for achieving that.. could u please help
Newbie
@Newbie: If you can edit your post to describe what you're actually trying to accomplish, maybe we can help you with that instead. Taking a *wild* guess, it seems that your table isn't normalized properly.
Jon Seigel
Sir, I have already edited the expected output
Newbie
The reason nobody is willing to give you an answer is that (a) as Jon Seigel said, it would be super-hard to do; and (b) the fact that you're breaking apart values that are in the same record and re-associating them with values from different records strongly suggests that there's something wrong in the way you've constructed your data model. If you're willing to give a more concrete explanation of what you're trying to do, perhaps we could come up with a model that would work better.
Chris Wuestefeld