'Calculates the stats_demographic_aggregate for a specific parameter at a
specific location.
@param location_id: the location record ID
@param parameter_id: the parameter record ID
@param total_id: the parameter record ID for the percentage calculation
@param start_date: the start date of the time period (as string)
@param end_date: the end date of the time period (as string)'

@staticmethod
def stats_demographic_update_location_aggregate(location_level, location_id, parameter_id, total_id, start_date, end_date):

    db = current.db
    dtable = current.s3db.stats_demographic_data
    atable = db.stats_demographic_aggregate
    child_locations = current.gis.get_children(location_id, location_level)
    child_ids = [row.id for row in child_locations]
    query = ((((dtable.parameter_id == parameter_id) & (dtable.deleted != True)) & dtable.location_id.belongs(child_ids)) & (dtable.approved_by != None))
    if (end_date == 'None'):
        end_date = None
    else:
        query &= (dtable.date <= end_date)
    rows = db(query).select(dtable.value, dtable.date, dtable.location_id, orderby=(dtable.location_id, (~ dtable.date)))
    last_location = None
    values = []
    append = values.append
    for row in rows:
        new_location_id = row.location_id
        if (new_location_id != last_location):
            last_location = new_location_id
            append(row.value)
    values_len = len(values)
    if (not values_len):
        return
    values_sum = sum(values)
    percentage = ((100 * values_sum) / values_total)
    values_percentage = round(percentage, 3)
    query = ((((atable.location_id == location_id) & (atable.parameter_id == parameter_id)) & (atable.date == start_date)) & (atable.end_date == end_date))
    exists = db(query).select(atable.id, limitby=(0, 1)).first()
    attr = dict(agg_type=2, sum=values_sum, percentage=values_percentage)
    if exists:
        db(query).update(**attr)
    else:
        atable.insert(parameter_id=parameter_id, location_id=location_id, date=start_date, end_date=end_date, **attr)
