-1

Experts,

I have this data -

ID       |  buckets      | SUM (USD)|
--------- --------------- ---------
1        | 10 - 20       | 500      |
--------- --------------- ---------
1        | 30 - 40       | 100      |
--------- --------------- ---------
2        | 30 - 40       | 300      |
--------- --------------- ---------

Now the output that I'm trying and failing to get in PSQL when it is so easy in Excel ->

ID       |. 10-20        | 30-40    | Total_USD |
--------- --------------- ---------  -----------
1        |   500         |  100     |    600    |
--------- --------------- ---------  -----------
2        |               |  300     |    300    | 
--------- --------------- ---------  -----------

Would appreciate if you can guide me/ send me the right direction

1
  • I found some resources showing PIVOT might work - since in excel that is exactly what's working. BUT I can't install package/import since I have read only access.
    – NasahT
    Aug 17, 2022 at 20:48

1 Answer 1

2

Pivot (or crosstab) can be done using filtered aggregation:

select id, 
       sum("sum") filter (where buckets = '10 - 20') as "10 - 20",
       sum("sum") filter (where buckets = '30 - 40') as "30 - 40",
       sum("sum") as total
from the_table
group by id
order by id;       

But in general, SQL isn't designed for this type of reporting. Doing that in Excel (or any other reporting software) is a much better solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.