2014-12-03 33 views
0

我正在努力尝试在一列中根据列中的值在'select'语句中创建3个单独列的查询。SQL查询将列表转换为多列

我的例子:

我有两个表

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 

如何获得第二个测量列?任何帮助不胜感激。

贝基

回答

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 
+0

太好了,非常感谢。不是每一行都有湿重和坡度的测量值,所以后面的选项是合适的。 ...我注意到,虽然这需要一段时间来查询(一次我添加了其他几种类型的测量)。谢谢 – user3770062 2014-12-04 08:11:45

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 
+0

太好了,这也适用(除了上面的a_horse_with_no_name解决方案)。我有一些布尔值和其他字符。 (即“then value_real”将是“then_value_char”或“then_value_bool”)。这些显然不能使用“max(case)”操作符,非数字类型的解决方案是什么?再次感谢您的支持,非常感谢 – user3770062 2014-12-04 08:15:44

+0

@ user3770062 - 您可以对任何数据类型使用'case'。试一试,它应该工作。 – sgeddes 2014-12-04 13:14:47