views:

928

answers:

3

How can I rewrite the query "select col1 from tbl1" so it splits the results into three columns - each column sorting the results vertically?

So if the data I'm getting back is:

aaa
bbb
ccc
ddd
eee
fff
ggg

I need the query to return it as:

aaa  ddd  ggg
bbb  eee
ccc  fff

Is this possible? Thanks

+8  A: 

In truth, this should not be done in SQL. Unless the pairing of aaa, ddd, and ggg has some meaning then this is client-side formatting and shouldn't be done on the server.

EDIT:

In the interests if an intellectual exercise, something like this seems to work.

select
    f1.data, f2.data, f3. data

from (select data, ROW_NUMBER() over (order by data) as row_num from your_table) f1

left join (select data, ROW_NUMBER() over (order by data) as row_num from your_table) f2 on f2.row_num = f1.row_num + (select CEILING(COUNT(1) / 3) + 1 from your_table)
left join (select data, ROW_NUMBER() over (order by data) as row_num from your_table) f3 on f3.row_num = f1.row_num + (select CEILING(COUNT(1) / 3) + 1 from your_table) * 2

where f1.row_num between 1 and FLOOR((select COUNT(1) from your_table) / 3) + 1

But, again, I suspect that this is really something that should be done client-side, NOT in SQL.

Adam Robinson
I ended up doing this client-side. I was doing a mail merge with a tool that only takes a datatable (vb.net) and although I didn't like it, I wasn't sure how else to do it. I ended up creating a new datatable and filling it with data from the original query. Thanks for your help.
adam0101
+2  A: 

That seems like something that you should handle in the front end of your application. Unless there is a specific reason as to why you can't do that, I would suggest that you handle it there.

Tom H.
A: 

If it's just for formatting, then Adam is correct, you should do it client-side.

If it's data-related (I'm assuming aaa and bbb are not your actual data), then you can consider something like a SQL pivot to reorder the data.

Here's an example

jvenema