I currently have the following query:
WITH instances AS (
SELECT b.ldtc as date, a.fk_item_id, b.movement, a.quantity,
CASE WHEN b.movement = 'Inbound' THEN a.quantity ELSE -a.quantity END as absquantity
FROM inventory_resupplylogiteminstance a
INNER JOIN inventory_resupplylog b ON b.uid = a.fk_resupply_log_id
)
SELECT a.name,
SUM(CASE WHEN b.date < ('2018-10-10'::date) THEN b.absquantity END) as starting_balance,
SUM(CASE WHEN b.date > ('2018-10-10'::date) AND b.date < ('2018-10-12'::date) AND b.movement = 'aa' THEN b.absquantity END) as aa,
SUM(CASE WHEN b.date > ('2018-10-10'::date) AND b.date < ('2018-10-12'::date) AND b.movement = 'bb' THEN b.absquantity END) as bb,
SUM(CASE WHEN b.date > ('2018-10-10'::date) AND b.date < ('2018-10-12'::date) AND b.movement = 'cc' THEN b.absquantity END) as cc,
SUM(CASE WHEN b.date > ('2018-10-10'::date) AND b.date < ('2018-10-12'::date) AND b.movement = 'dd' THEN b.absquantity END) as dd,
SUM(CASE WHEN b.date < ('2018-10-12'::date) THEN b.absquantity END) AS ending_balance
FROM inventory_item a
LEFT JOIN instances b ON b.fk_item_id = a.uid
GROUP BY a.uid, a.name
ORDER BY a.name
As you can see, the 2nd-5th SUM lines are redundant in that they're querying for rows where b.date is between 2018-10-10 and 2018-10-12. Is there any way to rewrite my query so as to only have to write b.date > ('2018-10-10'::date) AND b.date < ('2018-10-12'::date) once and still be able to SELECT starting_balance and ending_balance on the same row?