views:

71

answers:

3

I am trying to pull data from a single column from my database but I would like to make it come out alphabetized and in two columns. I have tried floating the list but it ends up looking like this:
A_____B
C_____D
E_____F

I would like it to look like this:
A_____D
B_____E
C_____F

+1  A: 

the best approach would be to return it as single column a-z from the database and in the application reformat and display it as you would like

KM
A: 

You said float so I assume you're writing html... You'll have to split the results in half. Something like this...

<div id="column-1" style="width: 49%; float: left;">
  <!--first half here-->
</div>
<div id="column-2" style="width: 49%; float: left;">
  <!--second half here-->
</div>
camomileCase
A: 

I agree with KM, make the developers do some work--this kind of stuff HAS to be easier to do in procedural code. But if they're all on vacation (like me in 2 hours), this frankenstein query would work. This was done in SQL 2005 using common table expressions, but something similar (if even more awkward) using temp tables would work.

;WITH SourceData (ProductId, EvenOdd)
 as (select ProductId, row_number() over (order by ProductId) EvenOdd
     from Products)
,OddData (ProductId, OrderNum)
  as (select ProductId, row_number() over (order by EvenOdd) OrderNum
  from SourceData
  where EvenOdd%2 = 1)
,EvenData (ProductId, OrderNum)
  as (select ProductId, row_number() over (order by EvenOdd) OrderNum
  from SourceData
  where EvenOdd%2 = 0)
SELECT od.ProductId, ed.Productid
 from OddData od
  left outer join EvenData ed
   on ed.OrderNum = od.OrderNum

"ProductId" is the column you want to sort. Doesn't matter if there are duplicates or gaps in your sequence. If there's an odd number of items, that last right-hand value will be null. You could even expand this to have more than 2 columns returned.

Philip Kelley