with result as (
SELECT 
    * 
FROM 
    `fao-maps.fao_esa_smallholders.vw_esa_survey_data_portrait_production_gaul_2` 
WHERE   
    (@c_year = "all" or @c_year = c_year)
AND 
    (var_type = @variable_type))

SELECT * except(rn)
FROM
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Country,admin_level_1, adm2_code  , admin_level_2 ORDER BY year DESC) rn
    FROM result
) t
WHERE rn = 1
order by 1,2,4;
