我有一个表,其中包含以下数据:
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 |
我想执行crosstab()或case函数,但是我不知道如何使用它。我也看过其他关于同一件事的问题,但我不太明白。
我希望结果如下:
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 | | | |
基本上,在
mo
字段上旋转是我的目标。我希望每个type
都有自己的行,并将最大的mo
数累加为newimps
|newclicks
|newconv
|mo
,将所有其他oldimps
数累加为oldclicks
|oldconv
|我将使用哪种类型的查询/函数来执行所需的结果?
最佳答案
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;
sql fiddle demo
关于sql - 我是否使用crosstab()或函数达到所需结果的情况[postgresql],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19639470/