Pivot Table in Ruby

Ruby — Dillon @ 10:42 pm

Sometimes you need to transpose data from columns to rows or vice-versa. In the SQL world, this is called a pivot table. Usually this happens when you’re coming from a key-value store and want to turn it into something more structured but it can also happen in poorly designed or legacy databases. The idea is pretty simple, pivot the data from rows into columns. For example, here’s a listing of CDs:

-------------------------------------
DJ Shadow       |  electronica
DJ Shadow       |  1996
DJ Shadow       |  Endtroducing
The Avalanches  |  Since I Left You
The Avalanches  |  2000
The Avalanches  |  electronica
-------------------------------------

There are really only two CDs here but the data is presented to us as artist:attribute pairs. We want the data to look like this:

Artist         | Genre       | Album            | Year
------------------------------------------------------
DJ Shadow      | electronica | Entroducing      | 1996
The Avalanches | electronica | Since I Left You | 2000

(more…)

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.
(c) 2012 SQUARISM | powered by WordPress with Barecity