views:

53

answers:

3

Not sure if this is possible, but there might be a creative approach...

Given this data in SQL Server 2005:

AAA
AAA
BBB
BBB
CCC
CCC
DDD
DDD

How could I return a result set sorted in a pattern like this:

AAA
BBB
CCC
DDD
AAA
BBB
CCC
DDD

A: 

Don't know if it works, but in Oracle I would try to create a view in which you use ROWNUM in the query of your view.

Then query the view and sort on:

  • rownum modulo 2
  • the string

I don't have my database at hand here to test this, but this tip might give you some ideas.

Patrick
+5  A: 

If your column were called "col", and your table were named "table", I would try something like this:

WITH Indexes AS (
    SELECT 
    ROW_NUMBER() OVER (PARTITION BY col ORDER BY col) as __row,
    col
    FROM table)
SELECT col
FROM Indexes
ORDER BY __row, col;
Dave Markle
+1: This is more general than my solution which works only for 2 copies.
Mark Byers
wow - that's awesome!
Daniel
+1 I'd never have thought of using "PARTITION BY col ORDER BY col"
gbn
Actually, it really doesn't matter what you order by, because all of the values are the same within any given partition. I just chose col because it was convenient. You could order by anything.
Dave Markle
A: 

Mysql, assuming you have table T(a varchar); with the data you provided:

select @t:=a from T order by @t <> a;

it works :-)

Qwerty
Oops... just saw you need SQL Server 2005
Qwerty