def chunking_query_by_n_users(table_name='%(table_name)s', max_chunksize=50000
    ):
    """
    Create a chunk_id which is based on the unique users (caller_id) and
    the maximum size of users per chunk defined in attributes.

    Inputs
    ------
    table_name : Name of the table the query is supposed to run on,
                 defaulting to '%(table_name)s', i.e. no substitution.
    max_chunksize : Maximum number of users per chunk.

    Output
    ------
    Crosswalk between caller_id and chunk_id.
    """
    query = """
        SELECT
          caller_id,
          -- as soon as chunk limit is reached the id increases by 1
          SMALLINT((counter-1) / %(max_chunksize)s)+1 as chunk_id
        FROM
        (
          SELECT
            caller_id,
            ROW_NUMBER() OVER (ORDER BY caller_id) as counter -- no ties
          FROM %(table_name)s
          GROUP BY caller_id
        )
    """
    return query % {'table_name': table_name, 'max_chunksize': max_chunksize}
