Assumed the table name is products - this is a query which sum the value of the most recent record per group
SELECT sum(p1.value) as total
FROM products p1 LEFT JOIN products p2
ON (p1.product_code = p2.product_code AND p1.date < p2.date)
WHERE p2.product_code IS NULL;
In Query Builder
$total = DB::table('products as p1')
->selectRaw('SUM(p1.value) as total')
->leftJoin('products as p2', function ($join) {
$join->on('p1.product_code', '=', 'p2.product_code')
->where('p1.date', '<', 'p2.date');
})
->whereNull('p2.product_code')
->value('total');
If your database version supports window functions, then:
WITH ranked AS (
SELECT products.*,
RANK() OVER (PARTITION BY product_code ORDER BY date DESC) AS rn
FROM products
)
SELECT sum(value) as total
FROM products
WHERE rn = 1;