Groovy:从.eachRow()调用中访问变量来填充百分比计算

时间:2015-03-30 11:05:19

标签: sql groovy

我目前有两个查找特定值的查询,我需要从中收集结果并计算百分比。但是,我无法确定如何访问每个查询.eachRow()调用中的特定变量,以便填充我的百分比计算方法。

eachRow调用如下:

def resultOne = db.eachRow(firstQuery, ["${startDate} 00:00:00".toString(),  ${endDate} 23:59:59".toString()]) {
    String ticketsMetric = it.metricName
    String ticketsValue = it.ticketValue.intValue()
    reportMetricsWithValues[ticketsMetric] = ticketsValue
    table.addData([metric:ticketsMetric, value: ticketsValue])
}

def resultTwo = db.eachRow(secondQuery, ["${startDate} 00:00:00".toString(), "${endDate} 23:59:59".toString()]) {
    String ticketsMetric = it.metricName
    String ticketsValue = it.ticketValue.intValue()
    reportMetricsWithValues[ticketsMetric] = ticketsValue
    table.addData([metric:ticketsMetric, value: ticketsValue])
}

这些值填充报告。我想做点什么:

def firstCalc = resultOne.ticketsValue
def secondCalc = resultTwo.ticketsValue
def percentage = (secondCalc/firstCalc*100) + "%"
table.addData([metric:"Percentage", value: percentage])

但是,我不确定如何从.eachRow()

中访问这些值

1 个答案:

答案 0 :(得分:0)

您无法访问其范围之外的本地变量。定义eachRow范围之外的变量。例如:

def firstCalc = 0
def secondCalc = 0

db.eachRow(firstQuery, ["${startDate} 00:00:00".toString(),  ${endDate} 23:59:59".toString()]) {
    String ticketsMetric = it.metricName
    String ticketsValue = it.ticketValue.intValue()
    firstCalc += it.ticketValue.intValue()
    reportMetricsWithValues[ticketsMetric] = ticketsValue
    table.addData([metric:ticketsMetric, value: ticketsValue])
}

db.eachRow(secondQuery, ["${startDate} 00:00:00".toString(), "${endDate} 23:59:59".toString()]) {
    String ticketsMetric = it.metricName
    String ticketsValue = it.ticketValue.intValue()
    secondCalc += it.ticketValue.intValue()
    reportMetricsWithValues[ticketsMetric] = ticketsValue
    table.addData([metric:ticketsMetric, value: ticketsValue])
}

def percentage = (secondCalc/firstCalc*100) + "%"
table.addData([metric:"Percentage", value: percentage])