HomeMySQL技術項目 日々の情報から期間、単位を設定しデータ取得

日々の情報から期間、単位を設定しデータ取得

毎日データが入力されていないテーブルから週区切りの平均を求めるSQL ここでは、サンプルとして2008年1週目から2008年14週目までの各週の体重平均を求めます

syuu_noavg_weight
160.2
2null
360.9
460.29
5null
661.6
7null
862.64
9null
10null
11null
12null
13null
14null
テーブルデータ
テーブル名:t_weight(説明:体重管理)
wei_user_id :Varchar(4) wei_ymd :Date wei_weight :Float
0001 2008/01/01 60.2
0001 2008/01/17 60.9
0001 2008/01/26 60.3
0001 2008/02/05 61
0001 2008/02/06 62.2
0001 2008/02/24 62.1
0001 2008/02/25 63.2
主キー
wei_user_id、wei_ymd


SQL文

select
 syuu_cal.syuu_no
 ,v_data.avg_weight
from
 (
 select 1 as syuu_no
 union
 select 2 as syuu_no
 union
 select 3 as syuu_no
 union
 select 4 as syuu_no
 union
 select 5 as syuu_no
 union
 select 6 as syuu_no
 union
 select 7 as syuu_no
 union
 select 8 as syuu_no
 union
 select 9 as syuu_no
 union
 select 10 as syuu_no
 union
 select 11 as syuu_no
 union
 select 12 as syuu_no
 union
 select 13 as syuu_no
 union
 select 14 as syuu_no
) syuu_cal
left outer join
(
select
 truncate(((to_days(wei_ymd) - to_days('2008/01/01')) / 7),0)+1 as syuu_no
 ,truncate(avg(wei_weight),2) as avg_weight
from
 t_weight
where
 wei_user_id = '0001'
group by
 truncate(((to_days(wei_ymd) - to_days('2008/01/01')) / 7),0)
) v_data
on (syuu_cal.syuu_no = v_data.syuu_no) 

プログラムでSQL文を生成する場合は、「syuu_cal」をループで作成すると効率が良いです。




ページトップへ

データベース

サーバ

Copyright (C) MadCap. All Rights Reserved.