Postgres: distinct aggregation within group by

Viewed 309

I have an events table with 3 columns:

  • sequence_id (the "offer" shown to many different cart sessions)
  • checkout_token (the cart session for a single visitor)
  • action (the type of event generated by the user with that cart session token)

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

1 Answers

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;
Related