我有一张存储森林图的测量值的表。该表具有以下标题:sql case在一列中返回多个未知字符串值
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()
功能。你在这里提出的是......可怕的(因为缺乏一个更好的词)并且不可能保持或正确使用(例如创建查询来分析数据)。如果您确实打算“尽可能保持灵活性”,则应该创建一个适用于简单查询的数据模型,而不是使难看的查询适合不可能的数据模型。对不起,不能再做更多... – Patrick 2014-12-05 14:58:09并提供一个小小的背景:我与森林信息系统公司合作多年,并且遇到了传统数据库,这些数据库看起来像您提议的那样诡异。这只是不好的做法。如果你喜欢你的森林,请拜托你的数据模型。 – Patrick 2014-12-05 15:00:36
我正在使用我的前任的数据模型,并将尽其所能。感谢您的意见,所有相同的 – user3770062 2014-12-05 15:33:23