新手问题 Rails 如何实现 二维表的显示及导出

brenda103 · 2016年01月11日 · 最后由 brenda103 回复于 2016年01月11日 · 1850 次阅读

数据库存入的是上图的基础表,现想根据此基础表生成下图表 现只知道由基础表通过 group_by 分组成一维表,如何才能实现像上图一样的二维表呢?还有如何才能把这张二维表导出(现只知道用 axlsx 导出基础表)?请指点迷津,小女子在此谢过!!!

这问题太简单我不知道怎么回答😁

select
  设备名称,
  count(1) 合计,
  sum(case 所在地 when '店1' then 1 else 0 end) 店1,
  sum(case 所在地 when '店2' then 1 else 0 end) 店2,
  sum(case 所在地 when '店3' then 1 else 0 end) 店3,
  sum(case 所在地 when '店4' then 1 else 0 end) 店4,
  sum(case 所在地 when '店5' then 1 else 0 end) 店5
from
  基础表
group by
  设备名称;

model:

create_table "sbs", force: :cascade do |t|
  t.string   "sbname" #设备名称
  t.string   "location" #所在地
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

controller :

def index
   #加载所有数据 
  @sb = Sb.all 
  #获取店名
  @loc = @sb.select(:location).distinct.order("location  ASC")
end

view :

<table>
    <tr>
        <th>名称 </th>
        <th> 合计</th>
        <% @loc.each do |loc|   -%>
            <th> <%= loc.location -%></th>
        <% end -%>  
    </tr>
    <tr>         
    <% @sb.select(:sbname).distinct.each do |item| %>
        <td><%= item.sbname -%></td>    
        <td><%=@sb.where(["sbname = ?", item.sbname]).count -%></td>   
        <% @loc.each do |loc|   -%>
          <td><%= @sb.where(["sbname = ? and location = ?", item.sbname,loc.location]).count   -%></td>
        <% end -%>          
    </tr>
    <%end %>
</table>
需要 登录 后方可回复, 如果你还没有账号请 注册新账号