古い質問ですが、とにかく: Ruby on Rails でこのようなものを偽造しました。私の目的では、うまく機能します。
def self.yearstats(attr)
# Determine number of columns
minyear = self.select("strftime('%Y', min(recorded_at)) AS minyear").first.minyear.to_i
maxyear = self.select("strftime('%Y', max(recorded_at)) AS maxyear").first.maxyear.to_i
# Stitch SQL query. Use explicit same column name to not confuse Rails' typecasting.
select_str = ["strftime('#{minyear}/%m/%d %H:%m', recorded_at) AS recorded_at"]
(minyear..maxyear).to_a.each do |y|
# avg because the table might have multiple rows per day
select_str += ["avg(case when strftime('%Y', recorded_at)='#{y}' then #{attr} end) AS value#{y}"]
end
self.select(select_str.join(",")).group("strftime('%m/%d', recorded_at)").all.collect {|row|
[row.recorded_at.utc.to_i*1000] + (minyear..maxyear).to_a.collect { |y| row.send("value#{y}") }
}
end
最初の列では、固定の最初の年を使用して (偽の) 日付を使用したことに注意してください。これにより、グラフ作成ルーチンは、日/月の表示だけでなく、「実際の」日付を取得します。これは少し汚れていますが、私の目的には適しています。(改善はまだ歓迎されています...)
と を取得する代わりに、SELECT DISTINCT.. を実行して、カテゴリの一意のリストを取得minyear
しmaxyear
、コードを適切に変更することをお勧めします。