=ARRAYFORMULA({QUERY(REGEXREPLACE(""&QUERY(A1:D,
"select A,B,sum(D) where A is not null group by A,B pivot C"),
"^0$", ),
"where Col3 is not null or Col4 is not null");
{"Grand Total", "", INDEX(QUERY(A1:D,
"select sum(D) where A is not null pivot C"), 2)}})