I’m having the following data set (note that my database/schemata is somewhat complex so it’s not feasible to include all the details here)
This is a simplified version of my data which I extracted from my base tables and created a view.
workout_activity_record_id attribute_metric_id attribute_metric_value workout_exercise_set_created_on 234 17 10 2012-02-06 00:00:00 234 18 30 2012-02-06 00:00:00 234 17 20 2012-03-03 00:00:00 234 18 12.9 2012-03-03 00:00:00 234 17 20 2012-04-02 00:00:00 234 18 40 2012-04-02 00:00:00 . . . (So on for further workout_activity_record_ids)
I need to compute (look up in the data to understand better)
Grand Total = (10 * 30) + (20 * 12.9) + (20 * 40)
grouped by month.
A basic approach here that would aid in multiplying is transpose the rows into columns. So the above structure would become –
workout_activity_record_id ex17 ex18 workout_exercise_set_created_on 234 10 30 2012-02-06 00:00:00 234 20 12.9 2012-03-03 00:00:00 234 20 40 2012-04-02 00:00:00 . . . . . (And so on for remaining workout_activity_record_ids)
For this, I went through several SO posts and after trying out various viable/non-viable (:D) options, I came up with the following query.
SELECT
CASE attribute_metric_id
WHEN '17' THEN attribute_metric_value END AS 'ex17',
CASE attribute_metric_id WHEN '18' THEN attribute_metric_value END AS 'ex18',
workout_exercise_set_created_on
FROM exercise_attribute
WHERE workout_activity_record_id =234
And the actual output I got was
workout_activity_record_id ex17 ex18 workout_exercise_set_created_on 234 10 NULL 2012-02-06 00:00:00 234 NULL 30 2012-02-06 00:00:00 234 20 NULL 2012-03-03 00:00:00 234 NULL 12.9 2012-03-03 00:00:00 234 20 NULL 2012-04-06 00:00:00 234 NULL 40 2012-04-02 00:00:00
Can anyone shed some light over this? I’d be grateful. Thanks!
This computes the grand total for you, grouped by year and month:
SQL Fiddle Example
Output