我有以下數據集(請注意,我的數據庫/模式有點複雜,所以在這裏包含所有細節並不可行)將行轉換爲列 - 面臨的一個問題。
這是我從我的基表中提取的數據的簡化版本並創建了一個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)
我需要計算(查找數據,更好地瞭解)
Grand Total = (10 * 30) + (20 * 12.9) + (20 * 40)按月分組。
這裏有助於乘法的基本方法是將行轉置爲列。因此,上述結構將成爲 -
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)
對於這一點,我通過幾個竟然職位,嘗試了各種可行的/非後是活的(:d)選擇,我想出了下面的查詢。
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
而且我得到的實際產量爲
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
任何人都流下了這一些輕?我會很感激。謝謝!
更新與組,按年,月 – RedFilter
謝謝!這對我來說已經足夠了。但是,你能否詳細解釋一下你如何構建這個查詢的各個部分? – verisimilitude
子查詢計算每個日期的小計。然後,外部查詢爲每年/每月的小計彙總。 – RedFilter