使用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"
是在六月十八号。