Tallboy
Tallboy

Reputation: 13467

Postgres: distinct aggregation within group by

I have an events table with 3 columns:

I want to output data in the following (NOT real numbers according to my image, just dummy example of output format):

sequence_id      action_0_unique_count    action_1_unique_count
1                5                        4
2                2                        0

im trying to count the DISTINCT number of event types (action enum column) PER checkout session, grouped by sequence_id

enter image description here

Here's an image example of which rows I'm trying to select for column 2. Column 3 would be similar, except WHERE action = 1

Upvotes: 3

Views: 1255

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270843

You can use conditional aggregation:

select sequence_id,
       count(distinct checkout_token) filter (where action = 0),
       count(distinct checkout_token) filter (where action = 1)
from events
group by sequence_id;

Upvotes: 5

Related Questions