Skip to content
Advertisement

Postgresql – Looping through array_agg

I have a table from which I need to calculate the number of times intent_level changes for each id.

Sample Table format :

I couldn’t figure out how to loop through array_agg and compare consecutive elements. Below I tried using array_agg, but then I don’t know how to loop through it and compare consecutive elements.

which gives output :

Desired output is :

2 (since value changes from "" to status(1 to 2) and status to category(3 to 4))

1 (since value changes from status to ""(2 to 3))

CREATE AND INSERT QUERIES :

Advertisement

Answer

Use lag() and aggregate:

Here is a db<>fiddle.

Arrays seem quite unnecessary for this.

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