The best way to ahieve this is in a stored procedure in the database.
Just create a method on your model class that will run the stored proc,
that way your controllers and rake tasks etc... can have access to the
functionality if you want them to
Let the database do the job it's designed to do and let your models do
their bit, you will get a much better performance.