1

我有一个包含以下数据的表:

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

我将使用什么类型的查询/函数来执行我需要的结果?

4

1 回答 1

1
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

于 2013-10-28T17:00:27.643 回答