MODEL (
  name cleaned.psdalldata__commodity_pivoted,
  kind INCREMENTAL_BY_TIME_RANGE (
    time_column ingest_date
  ),
  start '2006-08-01',
  cron '@daily'
);

SELECT
  MAX(hkey) AS hkey,
  commodity_code,
  MAX(commodity_name) AS commodity_name,
  country_code,
  MAX(country_name) AS country_name,
  market_year,
  ingest_date,
  COALESCE(SUM(CASE WHEN attribute_name = 'Production' THEN value END), 0) AS Production,
  COALESCE(SUM(CASE WHEN attribute_name = 'Imports' THEN value END), 0) AS Imports,
  COALESCE(SUM(CASE WHEN attribute_name = 'Exports' THEN value END), 0) AS Exports,
  COALESCE(SUM(CASE WHEN attribute_name = 'Total Distribution' THEN value END), 0) AS Total_Distribution,
  COALESCE(SUM(CASE WHEN attribute_name = 'Ending Stocks' THEN value END), 0) AS Ending_Stocks,
  COALESCE(SUM(CASE WHEN attribute_name = 'Beginning Stocks' THEN value END), 0) AS Beginning_Stocks,
  COALESCE(SUM(CASE WHEN attribute_name = 'Total Supply' THEN value END), 0) AS Total_Supply,
  COALESCE(SUM(CASE WHEN attribute_name = 'Domestic Consumption' THEN value END), 0) AS Domestic_Consumption,
  COALESCE(SUM(CASE WHEN attribute_name = 'Domestic Demand' THEN value END), 0) AS Domestic_Demand,
  COALESCE(SUM(CASE WHEN attribute_name = 'Food Use' THEN value END), 0) AS Food_Use,
  COALESCE(SUM(CASE WHEN attribute_name = 'Industrial Use' THEN value END), 0) AS Industrial_Use,
  COALESCE(SUM(CASE WHEN attribute_name = 'Seed Use' THEN value END), 0) AS Seed_Use,
  COALESCE(SUM(CASE WHEN attribute_name = 'Waste' THEN value END), 0) AS Waste,
  COALESCE(SUM(CASE WHEN attribute_name = 'Feed Use' THEN value END), 0) AS Feed_Use
FROM staging.psdalldata__commodity
WHERE
  attribute_name IN (
    'Production',
    'Imports',
    'Exports',
    'Total Distribution',
    'Ending Stocks',
    'Beginning Stocks',
    'Total Supply',
    'Domestic Consumption',
    'Domestic Demand',
    'Food Use',
    'Industrial Use',
    'Seed Use',
    'Waste',
    'Feed Use'
  )
GROUP BY
  commodity_code,
  country_code,
  market_year,
  ingest_date
ORDER BY
  commodity_code,
  country_code,
  market_year,
  ingest_date