I’m having trouble manipulating certain information in a Select. I’ve tried a few ways but with no positive result.
Select:
select
cpri.sequential,
cpri.id,
coalesce(sum(pdr.something), 0) something,
...
from
cpri
inner join cpr on cpr.id = cpri.id
left join pdr on pdr.other_id = cpr.other_id
where
...
group by
cpri.sequential,
cpri.id,
...
order by
cpri.id desc
I have an output today as follows:
sequential|id |something|other_information
2637|880| 15000.00| ...
2635|880| 15000.00| ...
2636|880| 15000.00| ...
2638|880| 15000.00| ...
2624|876| 6000.00| ...
2625|876| 6000.00| ...
2611|870| 2000.00| ...
2612|870| 2000.00| ...
2613|870| 2000.00| ...
2614|870| 2000.00| ...
2571|858| 5000.00| ...
2572|858| 5000.00| ...
2569|858| 5000.00| ...
2570|858| 5000.00| ...
133| 68| 6366.90| ...
134| 68| 6366.90| ...
130| 66| 120.00| ...
129| 66| 120.00| ...
Target output:
sequential|id |something|other_information
2637|880| 15000.00| ...
2635|880| 0.00| ...
2636|880| 0.00| ...
2638|880| 0.00| ...
2624|876| 6000.00| ...
2625|876| 0.00| ...
2611|870| 2000.00| ...
2612|870| 0.00| ...
2613|870| 0.00| ...
2614|870| 0.00| ...
2571|858| 5000.00| ...
2572|858| 0.00| ...
2569|858| 0.00| ...
2570|858| 0.00| ...
133| 68| 6366.90| ...
134| 68| 0.00| ...
130| 66| 120.00| ...
129| 66| 0.00| ...
If we divide each of the equal ‘ids’ into groups, the ‘something’ column must have its value only in the first row and in the others it must be zero.
Is there a way to do this?
2
Answers
You can do this with a case expression using row_number, something like:
You can use the analytic function row_number:
for more information:
https://www.postgresql.org/docs/current/tutorial-window.html