2013-07-16 1 views
3

프로그래밍에 익숙하지만 다음과 같은 사항이 있습니다. postgresql 데이터베이스에서 데이터를 가져와 jqPlot 차트의 요약을 표시하는 레일 앱을 만들려고합니다. 내 검색어에 문제가 있습니다. 나는이 total_durations의 =처럼 뭔가를 포맷 할 것이다 차트 배열을 필요로 [[ "월", 3456], [ "2월", 21] 등]Postgresql 쿼리에서 Rails 3까지 배열 합계를 만드는 방법

여기에 테이블 내 DB에 usagedata라고이다 :

╔═══════════════╦═════════════╦═════════════════════╦════════════════╗ 
║ record_id ║ user_id ║  submit_time  ║ duration  ║ 
╠═══════════════╬═════════════╬═════════════════════╬════════════════╣ 
║    1 ║   6 ║ 2012-09-19 22:18:58 ║  45  ║ 
║    2 ║   1 ║ 2012-09-19 22:45:59 ║  0   ║ 
║    3 ║   5 ║ 2012-09-20 01:57:52 ║  3987  ║ 
║    4 ║   8 ║ 2012-09-18 03:47:53 ║  34  ║ 
║    5 ║   9 ║ 2013-01-26 20:38:03 ║  678  ║ 
║    6 ║   1 ║ 2013-01-26 23:41:44 ║  56  ║ 
║    7 ║   2 ║ 2013-01-27 02:10:41 ║  100  ║ 
╚═══════════════╩═════════════╩═════════════════════╩════════════════╝ 

1. 부분적인 방법
내가 모델 usagedata.rb 있습니다

class Usagedata < ActiveRecord::Base  
    def self.by_month  
    h = Usagedata.calculate(:sum, :duration, :conditions => {  
    :submit_time => (Time.now.all_year) },  
    :order => "EXTRACT(month FROM submit_time)",  
    :group => ["EXTRACT(month FROM submit_time)","EXTRACT(year FROM submit_time)"]) 

    end 
end  

사기꾼 troller의 usagedata_controller.rb :

class UsagedataController < ApplicationController  
    def index  
    end 
    private 
    def set_usagedata 
     @usagedata = Usagedata.find(params[:id]) 
    end 
    def usagedata_params 
     params[:usagedata] 
    end 
end 

그리고보기 index.html.haml : 뷰의

%br=h = Usagedata.by_month 

출력입니다 : 내가 배열을 얻을 수있는 방법

{[1.0, 2013.0]=>135776897, [2.0, 2013.0]=>100620585, [3.0, 2013.0]=>162980319, [4.0, 2013.0]=>26916589, [5.0, 2013.0]=>18793323, [6.0, 2013.0]=>9250440, [7.0, 2013.0]=>5011563, [12.0, 2012.0]=>24092} 

total_durations=[["Jan", 3456],["Feb", 21], etc] 데이터베이스 테이블에 따라 month은 submit_time 필드에서 가져오고 다른 숫자는 매월 만든 기간의 합계입니다. 심지어는 배열 total_durations=[["1.0, 2013.0", 135776897],["2.0, 2013.0", 100620585], etc] 도움이 될 것입니다.

2. 내가 DB에 필요한 어떤 출력을 얻을 수 있었다
부분 방법 :

select to_char(submit_time,'Mon') as mon, 
    extract(year from submit_time) as yyyy, 
    sum("duration") as "Total_Duration" 
from usagedata 
group by 1,2 

하지만 어떻게 레일에 배열에 쿼리의 출력을 얻을 수 있나요?

%br=Usagedata.select("duration, extract (month from submit_time) as month, extract(year from submit_time) as year, SUM(submit_time) as total").group(1,2) 

을하지만 그것은 단지 라인을 인쇄하는 것 :

내 html.haml 페이지에서이 작업을 시도했습니다

@fetch = [] 
    Usagedata.select("extract (month from submit_time) as month, extract(year from submit_time) as year, SUM(duration)").group_by(1,2).each do |ph| 
    @fetch << [ph.month.to_f, ph.year, ph.sum] 
end 
:
#<ActiveRecord::Relation::ActiveRecord_Relation_Usagedata:0x007f1c10997518> 

이 또한 나의 컨트롤러에 추가하려

하지만이 말은 단지 오류입니다.

PG::Error: ERROR: column "usagedata.submit_time" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT extract (month from submit_time) as month, extract(ye...^: SELECT extract (month from submit_time) as month, extract(year from submit_time) as year, SUM(duration) FROM "usagedata" 

3. 부분 방법
여기 Discribed : http://railsforum.com/viewtopic.php?id=27205
controller.rb :

@usagedata_groups = Usagedata.find(:all, 
    :select => 'submit_time, wall_duration, id', 
    :conditions => {:machine_name_id => ["1"]},).group_by{|usagedata| usagedata.submit_time.beginning_of_month} 

    @fetch = [] 
    Usagedata.find(:all, 
    :select => 'submit_time, wall_duration, id', 
    :conditions => {:machine_name_id => ["1"]},).group_by{|usagedata| usagedata.submit_time.beginning_of_month}.keys.sort.each do |month| 
     @fetch << month.strftime("%B %Y") 
     @fetch << month.collect(&:wall_duration).sum 
    end 

index.html을.컨트롤러 라인 @fetch << month.collect(&:wall_duration).sum없이 HAML

%table 
    %tr   
    %th  
    - @usagedata_groups.keys.sort.each do |month|   
     %tr 
     %td 
      #{month.strftime("%B %Y")}   
     %td 
      #month.collect(&:wall_duration).sum 
    %table 
    %tr 
    %th Show @fetch content:  
    - @fetch.each do |co| 
     %tr 
     %td=co 

출력 : 그 라인

February 2013  98503443 
March 2013   162980319 
April 2013   26916589 
May 2013    18793323 
June 2013    9250440 
July 2013    5399525 

Show @fetch content 
February 2013 
March 2013 
April 2013 
May 2013 
June 2013 
July 2013 

는 오류가 발생합니다 :

NoMethodError in UsagedataController#index 
undefined method `collect' for Fri, 01 Feb 2013 00:00:00 UTC +00:00:Time 

도와주세요!

+0

더 나은 성능을 얻지 못했지만 쿼리가 정상적으로 작동하지 않습니다. 그러나 레일스 액티브 레코드를 편리하게 사용하려면 계속하십시오. 여기에 필요한 모든 정보가 있습니다. http://guides.rubyonrails.org/active_record_querying.html – bluehallu

+0

루비에서 날짜와 합계 기간을 구문 분석하면 성능이 향상 될 수 있습니다. –

+0

@Hallucynogenyc 나는 더 많은 지시를 위해 나의 포스트를 편집했다. 나는 지금 바로 배열로 질의를하는 방법을 찾는 것처럼 보이지 않는다. :/ – user2586273

답변

0
#load data in struct like this 
# ["2"=>100620585, "3"=>135776897] 
items = Usagedata 
      .where(submit_time: Time.now.all_year) 
      .order('EXTRACT(month FROM submit_time)') 
      .group('EXTRACT(month FROM submit_time)') 
      .sum(:duration) 

# and regroup it right way 
# [["2", 100620585], ["3", 135776897]] 
result = items.map { |month, sum| [month, sum] } 
관련 문제