CREATE OR REPLACE VIEW max_version_stock_audit as  WITH cte AS (
         SELECT a.stock_take_id,
            a.version_number,
            b.item_id,
            b.uom_id,
            sum(b.quantity) AS totalquantity,
            rank() OVER (PARTITION BY a.stock_take_id, b.item_id, b.uom_id ORDER BY a.version_number DESC) AS rnk
           FROM stock_audit_entry_header a
             JOIN stock_audit_entry_line_items b ON b.stock_audit_entry_id = a.id
          GROUP BY a.stock_take_id, a.version_number, b.item_id, b.uom_id
        )
 SELECT stock_take_id,
    version_number,
    item_id,
    uom_id,
    totalquantity
   FROM cte
  WHERE rnk = 1;