forse con un group by with rollup ma dovresti descrivere meglio la tua situazione.