I’m trying to perform calculations, apply conditions for the calculated values and count results all in one query. The problem is that I don’t know how to refer to the calculated field from the conditions.
I have Issues.created_on field and I want to find statistics about how many issues were created each week during a range of weeks provided by user.
This how my query looks like in MySql:
mysql> SELECT status_id as group_id,
YEAR(created_on)*1000+WEEK(created_on,1) as range_value, count(*) as
noOfEntries FROM `issues` WHERE (`issues`.`project_id` IN (1)) GROUP
BY issues.status_id, range_value;
+----------+-------------+-------------+
| group_id | range_value | noOfEntries |
+----------+-------------+-------------+
| 1 | 2012031 | 2 |
| 5 | 2012015 | 1 |
+----------+-------------+-------------+
Here is my code (simplified):
# Range value is dynamic: "YYYYXXX", where YYYY is year and XXX could be week, month or day of year
range_value = "YEAR(created_on)*1000+WEEK(created_on,1)"
select = "#{range_value} as range_value, count(*) as noOfEntries"
grouping = "range_value"
# other conditions are provided by user, so we just add one here
conditions["range_value"] = range[:min]..range[:max]
rows = Issue.all(:select => select, :conditions => conditions, :readonly => true, :group => grouping)
But I get this error:
ActiveRecord::StatementInvalid (Mysql::Error: Unknown column 'issues.range_value' in 'where clause': SELECT YEAR(created_on)*1000+WEEK(created_on,1) as range_value, 'weeks' as range_type, count(*) as logged_hours, 1 as entries, 'priority_id' as grouping, issues.priority_id as group_id FROM `issues` WHERE (`issues`.`range_value` BETWEEN '2012012' AND '2012031' AND `issues`.`project_id` IN (1)) GROUP BY range_value, issues.priority_id ORDER BY 1 asc, 6 asc):
The code I’m trying to modify is not mine, so I cannot add any new fields or methods to the Issues object. So solution like this will not work for me, I guess.
I have found an example of code which actually helped:
So after a slight modification my code works: