Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Sorting within rows

Author  Topic 

colgie
Starting Member

18 Posts

Posted - 2010-06-16 : 13:20:04
I have a table in which each row is a category name followed by up to 50 subcategory names. The first field is called "category" and subsequent fields are called "subcategory1","subcategory2","subcategory3" etc etc
Is there a way to alphabetically sort the data within 1 row so that it comes back in order. I am using "ORDER BY" to sort the rows as a whole already but am having to use a clumsy ASP sort to sort within the rows. Any help would be greatly appreciated.

vijayisonly
Master Smack Fu Yak Hacker

1836 Posts

Posted - 2010-06-16 : 13:36:13
Pls post table structure, sample data and expected output.

Have a look at this link
How to ask: http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx
Go to Top of Page

robvolk
Most Valuable Yak

15732 Posts

Posted - 2010-06-16 : 13:59:11
Here's a proof of concept:
create table #a (i int, sub1 char(1), sub2 char(1), sub3 char(1), sub4 char(1))
insert #a values(1,'z','a','y','g')
insert #a values(2,'q','y','d','e')
insert #a values(3,'m','v','p','w')
insert #a values(4,'o','x','k','a')

select * from #a -- regular results

;with u(i, cat, z, sub) AS (
select i, cat, z, 'sub' + cast(row_number() over (partition by i order by i, z) as varchar) sub
from (
select i, sub1, sub2, sub3, sub4 from #a) ua
unpivot(z for cat in (sub1, sub2, sub3, sub4)) ub)
select i, [sub1], [sub2], [sub3], [sub4]
from (select i, z, sub from u) pa
pivot (max(z) for sub in ([sub1], [sub2], [sub3], [sub4]) ) pb -- results with sorted subs

drop table #a
However, I *STRONGLY* urge you to redesign this table and normalize the subcategories into a single column in another table. It's a lot easier to reassemble it with a pivot without having to unpivot it first.
Go to Top of Page
   

- Advertisement -