相関サブクエリの書き方が分かってきた
やっとできた。
FROM句に相関副問い合わせは指定できない*1 し、where句での指定では選択した値を持って来れない。
相関サブクエリでひたすら検索していたら
http://jutememo.blogspot.com/2010/11/sql-4-select.html
このページが見つかった。
なるほど、from句に書かずにselect句に直接書けばいいらしい。
で、昨日の続き *2 。同じテーブル構造で同じ結果を出力するSQLはこうなった。
select B.day, ( select sum( ( select col3 from sample where col2 <= B.day and col1 = c1s.v -- ※ order by col2 desc limit 1 )) as col3 from (select * from (values('A'), ('B')) as c1(v)) as c1s ) as col3 from ( select '2011-05-01'::Timestamp + ((days.d || ' days')::interval) as day from generate_series(0, 100) as days(d) ) as B where B.day < '2011-06-01' and B.day >= '2011-05-15' group by B.day order by B.day ; day | col3 ---------------------+------ 2011-05-15 00:00:00 | 2 2011-05-16 00:00:00 | 5 2011-05-17 00:00:00 | 5 2011-05-18 00:00:00 | 8 2011-05-19 00:00:00 | 8 2011-05-20 00:00:00 | 7 2011-05-21 00:00:00 | 7 2011-05-22 00:00:00 | 7 2011-05-23 00:00:00 | 7 2011-05-24 00:00:00 | 7 2011-05-25 00:00:00 | 5 2011-05-26 00:00:00 | 5 2011-05-27 00:00:00 | 5 2011-05-28 00:00:00 | 5 2011-05-29 00:00:00 | 5 2011-05-30 00:00:00 | 5 2011-05-31 00:00:00 | 5 (17 行)
※の箇所、ここではべた書きだけれど、コストは{col1の種類数 * selectサブクエリの行数}になり、selectサブクエリの中の検索でインデックスが効いていればだいぶ早くなる。