迭代记录并存储到数组中

时间:2016-07-01 16:57:35

标签: mysql ruby-on-rails

我需要显示一个像这样的表:

Table

我需要每个月按Tier分组的产品总数。但如果没有找到,我需要显示0。我正在使用

产品belongs_to:tier Tier has_many:产品

2 个答案:

答案 0 :(得分:0)

你不需要迭代

如果您尝试这样做,您将获得以下格式的结果

SELECT t.name as tier ,month((f.date)) as tmonth,count(*) FROM 
 File f inner join Tier t on t.id=f.tier_id group by tier,tmonth;

TIER1 | JAN |  7  | 
TIER1 | FEB | 5   |
TIER1 |  MAR| 20  | 
TIER2 | JAN |  17 |
TIER2 |FEB  | 14  |
TIER2 |  MAR| 3   |

然后

select tier,
  sum (case when tmonth = 'JAN' THEN cnt END) JAN,
  sum (case when tmonth = 'FEB' THEN cnt END) FEB,
  sum (case when tmonth = 'MAR' THEN cnt END) MAR,
-------------------------------------------------
-------------------------------------------------// 12 MONTHS
FROM (SELECT tier,(SELECT t.name as tier ,month((f.date)) as tmonth,count(*) AS cnt FROM 
 File f inner join Tier t on t.id=f.tier_id group by tier,tmont) T group by tier;

答案 1 :(得分:0)

要在一个查询中执行此操作,只需包含这些文件即可。这将预加载所有等级files关联。

在控制器中,以这种方式设置实例变量:

@tiers = Tier.includes(:files)

将此添加到您的Tier模型

def months_of_files 
  files.group_by{|file| file.date.strftime("%b")}
end

在索引页面上,类似这样的东西(这种语法是HAML)

%table
  %tr
    %th Tier
    - (I18n.t("date.abbr_month_names")).each do |mon|
      %th= mon
  = render @tiers

然后在视图中,当您渲染层(一行)时,您可以执行此操作

# tiers/_tier.html.haml
%tr
  %td= tier.name
  - (I18n.t("date.abbr_month_names")).each do |mon|
    %li= tier.months_of_files[mon].size
相关问题