2015-12-23 41 views
-3

我必須使用Ruby程序以下面指定的方式顯示數據.. 有人可以幫助我,我該怎麼做。必須對SQlcode或Ruby代碼進行更改。 的代碼如下位置:使用Ruby程序來顯示水平使用Ruby程序從數據庫中提取的數據

require 'sqlite3' 
#db=SQLite3::Database.open ('adaptive.db') 
class Database 
    @@db=SQLite3::Database.open 'adaptive.db' 
    def registered_users 
     @@db.execute(
     "Select strftime('%Y-%m',created_at) AS Month, count(uuid) as RegistredPeopleNo 
     from users 
     group by strftime('%Y-%m',created_at) 
     order by Month;") do |row| 
      p row 
     end 
     end 
     def registered_devices 
     @@db.execute(
     "Select strftime('%Y-%m',created_at) AS RegisteredMonth, 
      count(serial_number) AS RegisteredDevicesNo 
      from devices 
      group by strftime('%Y-%m',created_at) 
      order by RegisteredMonth;") do |row| 
       p row 
      end 
     end 
     def unregistered_users 
     @@db.execute(
     "Select strftime('%Y-%m',updated_at) AS Unregister, count(id) AS Id 
      from users 
      where id not in(Select user_id from devices) 
      group by strftime('%Y-%m',updated_at) 
      order by Unregister;") do |row| 
      p row 
      end 
     end 
     def unregistered_devices 
     @@db.execute(
     "Select strftime('%Y-%m',updated_at) AS Unregister,count(id) AS Id 
      from devices 
      where channel_id is null 
      group by strftime('%Y-%m',updated_at);") do |row| 
      p row 
     end 
    end 
    def device_per_user 
     @@db.execute(
     "select register AS NoOFMachines,count(id) as NoOFPeople 
     from(
     Select users.id AS id,count(devices.id) AS register 
     from users,devices 
     where users.id=devices.user_id 
     group by devices.user_id) 
     group by register;") do |row| 
      p row 
     end 
    end 
    end 

運行命令:

>irb 
>require './database' 
>db=Database.new 
>db.registered_users# 
The output is following: 
["2015-08",23] 
["2015-09",102] 
["2015-10",59] 
["2015-11",25] 

不過,我希望它像這樣顯示:

[["2015-08",23],["2015-09",102],["2015-10",59],["2015-11",25]] 

能有人幫我解決這個問題...在此先感謝

回答

1

將值存儲在數組中。 試試這個:

def registered_users 
    arr = [] 
    @@db.execute(
    "Select strftime('%Y-%m',created_at) AS Month, count(uuid) as RegistredPeopleNo 
    from users 
    group by strftime('%Y-%m',created_at) 
    order by Month;") do |row| 
    arr << row 
    end 
    p arr 
end 

更新:你不需要each環。可能下面的代碼會給你你想要的結果。

@@db.execute(
    "Select strftime('%Y-%m',created_at) AS Month, count(uuid) as RegistredPeopleNo 
    from users 
    group by strftime('%Y-%m',created_at) 
    order by Month;")` 
相關問題