sql查询将列表转换为多列

时间:2014-12-03 19:42:01

标签: postgresql-9.3

我正在努力尝试在'选择'中创建3个单独列的查询。来自一列的声明....基于列中的值。

我的例子:

我有两张桌子

forest.plots
columns = id(PK), a, b

forest.plot_measurements
columns = id(PK), plot_id (FK), measure_type (int), value_real

当plot_measurement有measure_type = 1时,这是一个斜率测量,如果measure_type = 2那么它是一个wet_weight测量

期望的结果是拥有一个具有标题的表:

plot_id, slope, wet_weight

我希望斜率列包含value_real中的值,其中measure_type = 2,我希望wet_weight列包含value_real中的值,其中measure_type = 1

我只获得一个值的代码:

select pm.value_real slope, pl.input_plot_id 
from forest.plot_measurement pm 
inner join forest.plots pl on pm.plot_id = pl.plot_id 
where pm.plot_measurement_type_id = 1 

如何获得第二个测量列?非常感谢任何帮助。

贝基

2 个答案:

答案 0 :(得分:0)

只需将表连接两次,将所需的type_id放入连接条件:

select pm.value_real slope, pl.input_plot_id, wg.value_real as wet_weight
from forest.plots pl
  join forest.plot_measurement pm on pm.plot_id = pl.plot_id pm.plot_measurement_type_id = 1 
  join forest.plot_measurement wg on wg.plot_id = pl.plot_id wg.plot_measurement_type_id = 2

这假设您每次测量都有一行。如果您不这样做,则需要将join更改为outer join

select pm.value_real slope, pl.input_plot_id, wg.value_real as wet_weight
from forest.plots pl
  left join forest.plot_measurement pm on pm.plot_id = pl.plot_id pm.plot_measurement_type_id = 1 
  left join forest.plot_measurement wg on wg.plot_id = pl.plot_id wg.plot_measurement_type_id = 2

答案 1 :(得分:0)

这被称为pivoting。实现它的一个选择是将maxcase

一起使用
select pl.plot_id, 
    max(case when pm.measure_type = 1 then value_real end) slope,
    max(case when pm.measure_type = 2 then value_real end) wet_weight
from forest.plots pl 
   inner join forest.plot_measurement pm on pm.plot_id = pl.plot_id 
group by pl.plot_id 
相关问题