'Calculate Subtotals using fixed categories in postgresql query
I have a query that returns the count and sum of certain fields on my tables, and also a total. It goes like this:
example:
with foo as(
select s.subcat as subcategory,
sum(s.cost) as costs,
round(((sum(s.cost) / (s.tl)::numeric )*100),2)|| ' %' as pct_cost
from (select ...big query)s group by s.subcat
)
select * from foo
union
select 'Total costs' as subcategory,
sum(costs) as costs,
null as pct_cost
from foo
order by...
| Category | Cost | Percentage |
|---|---|---|
| x_subcategory 1 | 5 | 0.5% |
| x_subcategory 2 | 1 | 0.1% |
| x_subcategory 3 | 18 | 1.8% |
| y_subcategory 1 | 7 | 0.7% |
| y_subcategory 2 | 10 | 1.0% |
| ... | ... | ... |
| Total | 41 | 5.8% |
And what I need to do for another report is to get the totals by Category. I have to assign these categories based on the value of the subcategory name, the point is how to partition the result so I can get something like this:
| Category | Cost | Percentage |
|---|---|---|
| x_subcategory 1 | 5 | 0.5% |
| x_subcategory 2 | 1 | 0.1% |
| x_subcategory 3 | 18 | 1.8% |
| X category | 24 | 2.4% |
| y_subcategory 1 | 7 | 0.7% |
| y_subcategory 2 | 10 | 1.0% |
| Y category | 17 | 1.7% |
With GROUP BY and GROUP BY GROUPING SET I don't get what I want, and with PARTITION I'm getting syntax errors, I'm able to use it in simpler queries but this one turned out to be very complicated and I wonder if it's possible to achieve this on a query on PostgreSQL.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
