【发布时间】:2020-12-09 05:27:21
【问题描述】:
我有 2 个表格 measure_timestamps 和 sensor_double_precision,格式如下:
id start_time stop_time
1 2020-02-22 2020-02-24
2 2020-02-25 2020-02-27
和
id sensor_name value_cal timestamp
1 start_freq 15 2020-02-23
2 stop_freq 18 2020-02-23
3 start_freq 15 2020-02-26
4 stop_freq 18 2020-02-26
我想要一个查看测量时间戳的视图,并且对于每个 start_time - stop_time 对,旋转(转置?)sensor_name 列,以便 start_freq 和 stop_freq 成为各自的列,并将相应的 value_cal 作为行。
所以我基本上希望 VIEW 看起来像这样:
id start_freq stop_freq timestamp
1 15 18 2020-02-23
2 15 18 2020-02-26
请注意 VIEW 中与 id 1 关联的时间戳如何位于 measure_timestamps 表中 id 1 的 start_time 和 stop_time 之间。
这样做的合理方法是什么?我不想为每个单独的 sensor_name 创建一个 VIEW,因为我有比这更多的传感器,而且它看起来不是很健壮。以下是我被推荐的一种方法,但它似乎不起作用,因为我可能做错了什么。
SELECT *
FROM crosstab('with current_data as (
select distinct on (mt.id)
mt.id, sdp.sensor_name, sdp.value_cal
from measurement_timestamps mt, sensor_double_precision sdp
order by mt.id desc
),
ids as (
select distinct id from current_data
),
sensor_names as (
select distinct sensor_name from current_data
)
select ids.id, sensor_names.sensor_name, current_data.value_cal
from ids cross join sensor_names
left join current_data on (ids.id=current_data.id and sensor_names.sensor_name=current_data.sensor_name)
order by ids.id,sensor_names.sensor_name') final_data (id integer, start_freq double precision,
stop_freq double precision, timestamp timestamp)
旁注 - start_freq 和 stop_freq 看起来不像传感器名称,但我正在使用遵循标准化形式的表格,因此我们将其称为 sensor_name。还有其他传感器我不担心这项任务。
编辑 - 来自下面建议的查询的结果:
id. start_freq stop_freq. timestamp
18 15 null "2020-07-09 20:03:38.937195+00"
19 null 18. "2020-07-09 20:03:39.051836+00"
20 null null "2020-07-09 20:03:39.171837+00"
21 null null "2020-07-09 20:03:39.287994+00"
22 null null "2020-07-09 20:03:39.287994+00"
23 15 null "2020-07-09 20:03:39.287994+00"
24 null 18 "2020-07-09 20:03:39.287994+00"
EDIT2 - 我在问题中附加的数据是示例数据,以便于讨论问题。结构和一切都与真实数据集相似。
【问题讨论】:
-
如果您只有两个传感器名称,则使用
case表达式。您提到不想要多个视图,所以这可能不是实际数据的样子? -
这基本上是数据的样子。还有其他sensor_names,但我并不真正关心它们,所以我将它们排除在外。我使用了
CASE语句,但它在数据点之间留下了NULL值。 -
如果第二个表中有超过两行与第一个表匹配怎么办?
-
@GordonLinoff 理想情况下忽略它们,但是,我总是可以选择我需要的任何东西,所以我愿意妥协是我必须将每个 sensor_name 作为一列旋转。确实有一些传感器属于你刚才描述的范围
标签: sql postgresql pivot-table crosstab