3

我是编程新手,但事情是这样的:我正在尝试制作 rails 应用程序,它从 postgresql 数据库中获取数据并在 jqPlot 图表中显示摘要,但我的查询遇到问题。我需要一个图表数组,其格式类似于 total_durations=[["Jan", 3456],["Feb", 21], etc]

这是我的数据库中名为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.部分方法
我有Model 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    

控制器用法data_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]根据数据库表获取数组,其中月份取自 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

但是我怎样才能得到查询的输出到 Rails 中的数组呢?

我已经在我的 html.haml 页面中尝试过这个:

%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)

但这只是打印线:

#<ActiveRecord::Relation::ActiveRecord_Relation_Usagedata:0x007f1c10997518>

还尝试将其添加到我的控制器中:

@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

但这只是给我一个错误:

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.这里描述的部分方法: 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.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

控制器中没有线路@fetch << month.collect(&:wall_duration).sum的输出:

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

请帮忙!

4

1 回答 1

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] }
于 2014-02-26T13:04:29.113 回答