Skip to content
Advertisement

postgresql total column sum

SELECT

I have a SELECT like this. I need to get something like the one shown above. That is, I need to get the total of one column. I’ve tried a lot of things already, but nothing works out for me.

Advertisement

Answer

If I understand correctly you want a result where extra row with aggregated value is appended after result of original query. You can achieve it multiple ways:

1. (recommended) the simplest way is probably to union your original query with helper query:

2. you can also use group by rollup clause whose purpose is exactly this. Your case makes it harder since your query contains many columns uninvolved in aggregation. Hence it is better to compute aggregation aside and join unimportant data later:

3. For completeness I just show you what should be done to avoid join. In that case group by clause would have to use all columns except amount (to preserve original rows) plus the aggregation (to get the sum row) hence the grouping sets clause with 2 sets is handy. (The rollup clause is special case of grouping sets after all.) The obvious drawback is repeating case grouping... expression for each column uninvolved in aggregation.

See example (db fiddle):

(To be frank, I can hardly imagine any purpose other than plain reporting where a column mixes id of number type with label Total of text type.)

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement