使用Ruby自動化遠程數據庫中的MySQL查詢,我希望根據下面找到的month
查詢的值拆分行。使用Ruby分割MySQL查詢的行並寫入CSV文件
這是針對所有基於開始日期的客戶在2014年6月份生成的每週(週三到下列Tueday)報告。雖然報告中沒有其他內容會發生變化,但是行的重複取決於該起始日期(在下面的case
聲明中進行了說明)。
請注意這裏使用的mysql2
,watir
和csv
寶石。
簡化代碼:
#!/usr/local/bin/ruby
require "mysql2"
require "watir"
require "csv"
puts "Initializing Report"
Mysql2::Client.default_query_options.merge!(:as => :array)
mysql = Mysql2::Client.new(:host => "1.2.3.4", :username => "user", :pass => "password", :database => "db")
puts "Successfully accessed db"
month = mysql.query("SELECT DATE_FORMAT(db.table.start, '%m') FROM db.table WHERE db.start.group = 1;")
day = mysql.query("SELECT DATE_FORMAT(db.table.start, '%d') FROM db.table WHERE db.start.group = 1;")
report = mysql.query("SELECT db.table.client, SELECT DATE_FORMAT(db.table.start, '%m/%d/%Y'), SELECT DATE_FORMAT(db.table.end, '%m/%d/%Y') FROM db.table WHERE db.start.group = 1;")
case month
when 5
# code splitting one row into four
when 6
if day <= 4
# code splitting one row into four using weekOf
elsif day >= 11 and day <= 17
# code splitting one row into three using weekOf
elsif day >= 18 and day <= 24
# code splitting one row into two using weekOf
else
# no splitting; only one row using weekOf
end
end
CSV.open("Report.csv", "wb") do |csv|
csv << ["Week of", "Client", "Start Date", "End Date"]
weekOf.zip(report).each {|row| csv << row.flatten}
end
puts "Results can be found in Report.csv"
電流輸出(如果我註釋掉case
聲明,去掉"Week of",
在CSV頭和只寫report
查詢到CSV):
Client, Start Date, End Date
companyrecordlabel, 05/20/2014, 07/09/2015
beeUrself, 05/27/2014, 02/01/2016
overflowStack, 06/04/2014, 12/11/2015
chapoChaps, 06/11/2014, 01/16/2016
Meds4U, 06/18/2014, NULL
.
.
.
我希望以下輸出:
Week of, Client, Start Date, End Date
06/04/2014, companyrecordlabel, 05/20/2014, 07/09/2015
06/11/2014, companyrecordlabel, 05/20/2014, 07/09/2015
06/18/2014, companyrecordlabel, 05/20/2014, 07/09/2015
06/25/2014, companyrecordlabel, 05/20/2014, 07/09/2015
06/04/2014, beeUrself, 05/27/2014, 02/01/2016
06/11/2014, beeUrself, 05/27/2014, 02/01/2016
06/18/2014, beeUrself, 05/27/2014, 02/01/2016
06/25/2014, beeUrself, 05/27/2014, 02/01/2016
06/04/2014, overflowStack, 06/04/2014, 12/11/2015
06/11/2014, overflowStack, 06/04/2014, 12/11/2015
06/18/2014, overflowStack, 06/04/2014, 12/11/2015
06/25/2014, overflowStack, 06/04/2014, 12/11/2015
06/11/2014, chapoChaps, 06/11/2014, 01/16/2016
06/18/2014, chapoChaps, 06/11/2014, 01/16/2016
06/25/2014, chapoChaps, 06/11/2014, 01/16/2016
06/18/2014, Meds4U, 06/18/2014, NULL
06/25/2014, Meds4U, 06/18/2014, NULL
.
.
.
爲了清楚起見:"Client"
爲companyrecordlabel
有四行,因爲它的"Start Date"
在五月份,而"Client"
Meds4U
只分成兩行,因爲它的"Start Date"
是在六月十八號。