> -----Original Message----- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] On Behalf Of > Carlos Rodriguez > Sent: Tuesday, July 25, 2006 12:14 AM > To: [email protected] > Subject: [PDX.rb] Top N Values Per Group > > Hi, > > I was hoping that someone could help me with something that's > been stumping me. > > I want to do, as the subject suggests, a top N values per > group query and I was wondering if there was a way to do it > "The Ruby Way" as opposed to writing a complicated > find_by_sql or some such. > > Here it is: > > Table Stuff > > id > title > category_id > > Table Categories > > id > name > > Stuff has many categories.
>From your pseudo-schema, it looks more like Stuff "belongs_to" Category. If you want Stuff to "have many" Categories, then categories needs to have the foreign key (altho I suspect if you didn't want "belongs_to" then you might want a has_and_belongs_to_many relationship between stuffs and categories). > > Let's say in the Categories table, I have the values "books, > dvds, music, games." > > What I want to do is select the first N from each category. > So one (or two or three..., depending what N is) from books, > music, dvd, and games. Can you be more specific about what puts a Stuff object at the top? Is there a "position" or is it a count of something? (hard to guess since "Stuff" could be anything...) > > I haven't found very many ways to do this in SQL without > writing complicated queries (see this example: > http://support.microsoft.com/ > kb/210039/en-us) so I was hoping that Ruby\Rails had some > magic coolness that I didn't know about. In any case, if you find that you're doing complex and/or expensive queries to get counts on something, you can always add a "count" column to a model and use "increment_counter" and "decrement_counter" http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M000871 - Jason > > Thanks to anyone in advance that can help me. > > If you're going to FOSCON, I'll see you there! > > Carlos Rodriguez > [EMAIL PROTECTED] _______________________________________________ PDXRuby mailing list [email protected] IRC: #pdx.rb on irc.freenode.net http://lists.pdxruby.org/mailman/listinfo/pdxruby
