【发布时间】:2016-06-07 03:43:27
【问题描述】:
使用 Ruby 从远程数据库自动执行 MySQL 查询,我希望根据下面找到的 month 查询的值拆分行。
这是为了根据开始日期为所有客户生成 2014 年 6 月的每周(周三至下周二)报告。虽然报告中的其他内容不会改变,但行的重复是基于该开始日期(在下面的 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 语句,请删除 CSV 标头中的 "Week of", 并仅将 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" 是在 5 月,而 "Client" Meds4U 只分成两行,因为它的 "Start Date" 是在 6 月 18 日.
【问题讨论】: