sql - understanding group by statements in rails -
given invoices table this:
invoice_date   customer        total          2012/01/01                   780                  2013/05/01                  3800  2013/12/01                  1500  2012/07/01       b              15  2013/03/01       b              21   say want both:
- the count of invoices of each customer of each year
 - the sum of amounts of invoices of each customer of each year
 - the max amount among invoices of each customer of each year
 
that is, in sql, easily:
select customer, year(invoice_date) invoice_year, max(total) max_total, sum(total) sum_amounts, count(*) invoices_num sum_total invoices group year(invoice_date), customer;   (the function extract year of date may year(date) or else depending on database server, on sqllite strftime('%y', invoice_date))
ok, i've tryed translate in rails/activerecord:
invoice.count(:group => 'customer')   this works, how can both count , sum , max? 
the idea i'm familiar (in sql) group by generates rows (well, correct, determines rows should exist in result table), , pass arbitrary number of aggregation functions applyed on every disaggregate set of rows behind single result row. e.g: group customer means: 1 row customer a, 1 row customer b; can pass how many aggregation function want: count(*), max(total), max(date), min(total) list common.
looking @ rails activerecord api seems you're supposed 1 function @ time, because group argument of count. , if want multiple aggregation functions, max, sum etc?
second attempt
irb> = invoice.select('customer, sum(total)').group('customer') invoice load (0.3ms) select customer, sum(total) total_group "invoices" group customer => [#, #]
that is: doesn't give field sum...
well does, doesn't printed out.  query i = invoice.select('customer, sum(total) sum_total').group('customer')
so i array(technically it's not array, not important here) containing result. i[0].sum_total give sum of first customer, of course should iterate want.
Comments
Post a Comment