with cte as (
select *, max(mo) over() as max_mo
from Table1
)
select
type, id, name,
sum(case when mo <> max_mo then imps else 0 end) as oldimps,
sum(case when mo <> max_mo then clicks else 0 end) as oldclicks,
sum(case when mo <> max_mo then conv else 0 end) as oldconv,
sum(case when mo = max_mo then imps else 0 end) as newimps,
sum(case when mo = max_mo then clicks else 0 end) as newclicks,
sum(case when mo = max_mo then conv else 0 end) as newconv
from cte
group by type, id, name
order by id;
Do I use a crosstab() or case when function to achieve results needed [postgresql]
-
01-07-2022 - |
문제
I have a table that has the following data:
type | id | name | imps | clicks | mo | conv |
---------+---- +-------|------|--------|------|------|
custom | 1 | new1 | 5 | 5 | 8 | |
default | 2 | new2 | 34 | | 8 | 5 |
other | 3 | old3 | 34 | 3 | 8 | |
other | 4 | old4 | 63 | 2 | 9 | 3 |
other | 3 | old3 | 23 | 9 | 9 | |
other | 3 | old3 | 12 | 1 | 10 | 1 |
I want to perform the crosstab() OR the case function but I just can't figure out how to use it. I've looked at other questions on here regarding the same thing but I can't quite grasp it.
I want the results to look like this:
type | id | name | oldimps | oldclicks | oldconv | newimps | newclicks | newconv |
---------+---- +-------|---------|-----------|-----------|---------|-----------|---------|
custom | 1 | new1 | 5 | 5 | | | | |
default | 2 | new2 | 34 | | 5 | | | |
other | 3 | old3 | 57 | 12 | | 12 | 1 | 1 |
other | 4 | old4 | 63 | 2 | 1 | | | |
Basically, pivoting on the mo
field is my goal. I want each type
to have its own row and for the highest number mo
to be accumulated to newimps
|newclicks
|newconv
and for all other numbers of mo
to be accumulated to oldimps
|oldclicks
|oldconv
What type of query/function would I go about using to perform the results I need?
해결책
제휴하지 않습니다 StackOverflow