Postgres - 可能是Crosstab?

时间:2013-02-13 22:00:17

标签: sql postgresql pivot crosstab

我有一个包含3列的表A -

date       | type | value
_________________________
2012-01-01 |  1   | 100
2012-01-01 |  2   | 200

2012-01-02 |  1   | 200
2012-01-02 |  2   | 300

2012-01-03 |  1   | 500
2012-01-03 |  2   | 10

是否有可能以这样的格式获取查询结果 -

date       |     type-1     |  type-2
_____________________________________
2012-01-01     100             200
2012-01-02     200             300

它看起来像是交叉表问题。不过不确定。 任何想法如何为此编写SQL?

1 个答案:

答案 0 :(得分:4)

您可以使用带有CASE表达式的聚合函数来获得结果:

select date,
  sum(case when type = 1 then value end) Type1,
  sum(case when type = 2 then value end) Type2
from yourtable
group by date

请参阅SQL Fiddle with Demo

你也可以多次加入你的桌子:

select t1.date,
  t1.value Type1,
  t2.value Type2
from yourtable t1
left join yourtable t2
  on t1.date = t2.date
  and t2.type = 2
where t1.type = 1

请参阅SQL Fiddle with Demo