PostgreSQL 案例在一列中返回多个未知字符串值



我有一个表格,用于存储森林图的测量值。该表具有以下标题:

id, plot_id, date, plot_measurement_type_id, value_type_id, value_int, value_real, value_bool, value_char, measurement_units_id

它旨在保留尽可能多的灵活性,因为多年来该地块将有许多不同类型的测量,并希望保留小表。

plot_measurement_type_id涉及不同类型的测量。总的来说,每个日期的每个图只有一个测量值。但是,当measurement_type_id = 5或6时,这是观察结果,可以有很多。有没有办法使用 case 语句(如下所示)并将所有观察结果(例如所有 5 个)连接起来放在一列中。我为此所做的解决方法是使用 max 和 min 将观测值放入单独的表中,但当有多个观测值时,这将不起作用。

我打算创建一个视图,以更易读的格式为用户显示数据......使用以下查询。

select pl.plot_id, 
    max(case when pm.plot_measurement_type_id = 1 then value_real end) slope,
    max(case when pm.plot_measurement_type_id = 2 and value_bool = TRUE then 'true' else 'false' end) burnt,
    max(case when pm.plot_measurement_type_id = 3 then value_real end) estimated_tree_canopy,
    max(case when pm.plot_measurement_type_id = 4 then value_real end) estimated_grass_cover,   
    max(case when pm.plot_measurement_type_id = 5 then value_char end) human_use,   
    min(case when pm.plot_measurement_type_id = 5 then value_char end) human_use2,
    max(case when pm.plot_measurement_type_id = 6 then value_char end) observations,
    max(case when pm.plot_measurement_type_id = 7 then value_char end) notes, 
    max(case when pm.plot_measurement_type_id = 9 then value_real end) wet_litter_weight,
    max(case when pm.plot_measurement_type_id = 11 then value_real end) dry_litter_weight,
    max(case when pm.plot_measurement_type_id = 10 then value_real end) wet_grass_weight,
    max(case when pm.plot_measurement_type_id = 12 then value_real end) dry_grass_weight,
    max(case when pm.plot_measurement_type_id = 13 then value_real end) altitude,
    max(case when pm.plot_measurement_type_id = 14 then value_char end) lcc
from forest.plots pl 
    inner join forest.plot_measurement pm on pm.plot_id = pl.plot_id 
group by pl.plot_id

是的。 在 Postgres 中,您可以使用 string_agg() 函数:

string_agg(case when pm.plot_measurement_type_id = 5 then value_char end, ', ') human_use2,

最新更新