You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按两列指定的时间索引范围聚合多行并拼接字段值

问题描述

现有数据表table1,记录每个传感器的时间范围:

sensor_idstart_time_indexend_time_index
114
126
213
224

另有数据表table2,记录每个传感器各时间点的数值:

sensor_idtime_indexvalue
11'A'
12'B'
13'A'
14'C'
15'D'
16'B'
21'B'
22'C'
23'D'
24'A'

需要生成目标表,将table1中每个时间范围内的table2数值按时间顺序拼接:

sensor_idstart_time_indexend_time_indexvalues_concatenated
114"ABAC"
126"BACDB"
213"BCD"
224"CDA"
解决方案

核心逻辑是先关联两张表筛选时间范围内的有效数据,再按table1的分组维度聚合拼接字符串,以下是主流SQL方言的实现:

MySQL/MariaDB

使用GROUP_CONCAT函数,指定排序保证拼接顺序:

SELECT
    t1.sensor_id,
    t1.start_time_index,
    t1.end_time_index,
    CONCAT('"', GROUP_CONCAT(t2.value ORDER BY t2.time_index SEPARATOR ''), '"') AS values_concatenated
FROM table1 t1
JOIN table2 t2 
    ON t1.sensor_id = t2.sensor_id
    AND t2.time_index BETWEEN t1.start_time_index AND t1.end_time_index
GROUP BY t1.sensor_id, t1.start_time_index, t1.end_time_index;

PostgreSQL

使用STRING_AGG函数:

SELECT
    t1.sensor_id,
    t1.start_time_index,
    t1.end_time_index,
    '"' || STRING_AGG(t2.value, '' ORDER BY t2.time_index) || '"' AS values_concatenated
FROM table1 t1
JOIN table2 t2 
    ON t1.sensor_id = t2.sensor_id
    AND t2.time_index BETWEEN t1.start_time_index AND t1.end_time_index
GROUP BY t1.sensor_id, t1.start_time_index, t1.end_time_index;

Spark SQL

使用STRING_AGG函数:

SELECT
    t1.sensor_id,
    t1.start_time_index,
    t1.end_time_index,
    CONCAT('"', STRING_AGG(t2.value, '' ORDER BY t2.time_index), '"') AS values_concatenated
FROM table1 t1
JOIN table2 t2 
    ON t1.sensor_id = t2.sensor_id
    AND t2.time_index BETWEEN t1.start_time_index AND t1.end_time_index
GROUP BY t1.sensor_id, t1.start_time_index, t1.end_time_index;

关键点说明

  • 通过sensor_id关联两张表,确保同一传感器的数据匹配
  • 用BETWEEN或t2.time_index >= t1.start_time_index AND t2.time_index <= t1.end_time_index筛选时间范围
  • 聚合时必须指定ORDER BY t2.time_index,保证拼接顺序与时间顺序一致
  • 外层的双引号拼接是为了匹配目标表格式,不需要可直接去掉

内容的提问来源于stack exchange,提问作者Guess601

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 04:15:10