1

I count the number of occurrences by the event type, so this is the SQL query:

select date(created), 
 event_type, 
 count(*) 
from public.event 
group by date(created), event_name

enter image description here

Is it possible to change the query in some way to "move" rows to the column to form this result table, each column corresponds an event type:

enter image description here

Ergest Basha
5,3693 gold badges8 silver badges22 bronze badges
asked Jan 26, 2024 at 21:20
2
  • 1
    The search term you want is "pivot". Commented Jan 27, 2024 at 0:40
  • 1
    Refer Pivot in PostgreSQL - explains how. Commented Jan 29, 2024 at 9:11

1 Answer 1

0

There are two ways to move the rows to columns either use Pivot or the case, for your example to move it to column using case,

select
date(created),
sum(case when event_type = 'a' then 1 else 0 end) a,
sum(case when event_type = 'b' then 1 else 0 end) b,
sum(case when event_type = 'c' then 1 else 0 end) c
from public.event 
group by 
date(created)

what you're going to do is creating a column with case and give a number 1 if it maches the event type and 0 if doesn't and you do that for the event depnds on the number of event you have if more than these check out pivot, then you are going to find the sum for each of these columns and group the result by the created date.

answered Feb 1, 2024 at 11:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.