0

I'm trying to avoid using straight up SQL in my Rails app, but need to do a quite large version of this:

SELECT ds.product_id,
  ( SELECT SUM(units) FROM daily_sales WHERE (date BETWEEN '2015-01-01' AND '2015-01-08') AND service_type = 1 ) as wk1,
  ( SELECT SUM(units) FROM daily_sales WHERE (date BETWEEN '2015-01-09' AND '2015-01-16') AND service_type = 1 ) as wk2
FROM daily_sales as ds group by ds.product_id

I'm sure it can be done, but i'm struggling to write this as an active record statement. Can anyone help?

1
  • Rewrite your sql query as SELECT ds.product_id, Sum(CASE WHEN date BETWEEN '2015-01-01' AND '2015-01-08' AND service_type = 1 THEN units ELSE 0 END) AS wk1, Sum(CASE WHEN date BETWEEN '2015-01-09' AND '2015-01-16' AND service_type = 1 THEN units ELSE 0 END) AS wk2, FROM daily_sales AS ds GROUP BY ds.product_id Feb 3, 2015 at 17:23

3 Answers 3

1

If you must do this in a single query, you'll need to write some SQL for the CASE statements. The following is what you need:

ranges = [ # ordered array of all your date-ranges
  Date.new(2015, 1, 1)..Date.new(2015, 1, 8),
  Date.new(2015, 1, 9)..Date.new(2015, 1, 16)
]

overall_range = (ranges.first.min)..(ranges.last.max)

grouping_sub_str = \
  ranges.map.with_index do |range, i|
    "WHEN (date BETWEEN '#{range.min}' AND '#{range.max}') THEN 'week#{i}'"
  end.join(' ')

grouping_condition = "CASE #{grouping_sub_str} END"
grouping_columns = ['product_id', grouping_condition]

DailySale.where(date: overall_range).group(grouping_columns).sum(:units)

That will produce a hash with array keys and numeric values. A key will be of the form [product_id, 'week1'] and the value will be the corresponding sum of units for that week.

1
  • Thanks, that's kind of close to the way it currently works but i'm trying to move away from it as it's not efficient enough as I have millions of lines in my DB. I'm also going to be grabbing something like 36 aggregate metrics.
    – Raoot
    Feb 4, 2015 at 12:25
0

Simplify your SQL to the following and try converting it..

SELECT ds.product_id,
, SUM(CASE WHEN date BETWEEN '2015-01-01' AND '2015-01-08' AND service_type = 1
    THEN units
    END) WK1
    , SUM(CASE WHEN date BETWEEN '2015-01-09' AND '2015-01-16' AND service_type = 1
    THEN units
    END) WK2 
FROM daily_sales as ds 
group by ds.product_id
1
  • Thanks, i'll definitely consider this if I can find a more Rails like way of doing this.
    – Raoot
    Feb 4, 2015 at 12:26
0

Every rail developer sooner or later hits his/her head against the walls of Active Record query interface just to find the solution in Arel.

Arel gives you the flexibility that you need in creating your query without using loops, etc. I am not going to give runnable code rather some hints how to do it yourself:

  1. We are going to use arel_tables to create our query. For a model called for example Product, getting the Arel table is as easy as products = Product.arel_table
  2. Getting sum of a column is like daily_sales.project(daily_sales[:units].count).where(daily_sales[:date].gt(BEGIN_DATE).where(daily_sales[:date].lt(END_DATE). You can chain as many wheres as you want and it will be translated into SQL ANDs.
  3. Since we need to have multiple sums in our end result you need to make use of Common Table Expressions(CTE). Take a look at docs and this answer for more info on this.
  4. You can use those CTEs from step 3 in combination with group and you are done!
2
  • thanks for this. I've seen references to Arel a few times but have never actually delved into it. I'll definitely take some time to get familiar with it.
    – Raoot
    Feb 5, 2015 at 11:23
  • It's totally worth it since it's much faster to let SQL do the calculation than ruby!
    – Yan Foto
    Feb 5, 2015 at 11:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.