SQL Server – Splitting a Deck of Cards and Returning Shuffled Results

sql servert-sql

Lets say I have a table with a deck of cards, numbered 01-52. I could return the top and bottom cards, as if I held each side of the union's select query in my left and right hands by doing a:

select top 26 * from DeckOfCards order by CardNumber desc
union all
select top 26 * from DeckOfCards order by CardNumber asc

It would be an even split.

But how could I have SQL Server intertwine the results returned, as if I had taken both portions of that union, one half in my left hand, and the other in my right, and shuffled them once like a deck of cards?

IE:
CardNumber 52, followed by 1, in the following sequence:
52, 1, 51, 2, 50, 3, 49, 4, etc…

This is not a homework question, just one of those things that passes through my mind when trying to get some shut eye. 🙂

Best Answer

A little math can help achieving this

SELECT CardNumber
FROM   DeckOfCards 
ORDER BY (1 - CAST(CardNumber / 27 as bit)) * (CardNumber* 2)
       + (CAST(CardNumber/ 27 as bit)) * (1 + (52 - CardNumber) * 2)

CAST(CardNumber / 27 as bit) returns 0 for the card number below 27 and 1 for the number above 26, using this it's possible to create a different order for the two different block:

  • (1 - CAST(CardNumber / 27 as bit)) * (CardNumber* 2) put the first 26 card in the even position, as the first member will be 1 for those card and 0 for the other
  • (CAST(CardNumber/ 27 as bit)) * (1 + (52 - CardNumber) * 2) will put the second 26 card in the odd position, e.g. (1 + (52 - CardNumber) * 2) will return odd values in descending order

SQLFiddle example with the order formula as a second column to see how it works