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

Oracle SQL:基于双区间范围与条件连接两表并添加Goal列

实现Main表与Section区间表的关联并生成Goal列

核心思路不需要转置Table1,而是基于Main表的Specified Depth,匹配Table1中所有满足「start深度 ≤ Specified Depth ≤ end深度」的section,再把这些section合并成Goal列的内容。以下是几种常用工具的具体实现方式:

1. Excel Power Query 操作步骤

  • 将Main表和Table1导入Power Query编辑器
  • 给Main表添加自定义列,筛选当前item对应的所有section:
    公式:Table.SelectRows(Table1, (r) => r[start深度] ≤ [Specified Depth] and r[end深度] ≥ [Specified Depth])
  • 再添加一个自定义列,把筛选出的section合并成逗号分隔的字符串:
    公式:Text.Combine(List.Transform([匹配的Sections], each _[section]), ", ")
  • 删除中间临时列,将结果加载回Excel

对应的Power Query M语言代码:

let
    源 = Excel.CurrentWorkbook(){[Name="Main"]}[Content],
    Table1 = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    添加匹配列 = Table.AddColumn(源, "匹配的Sections", each Table.SelectRows(Table1, (r) => r[start深度] ≤ [Specified Depth] and r[end深度] ≥ [Specified Depth])),
    生成Goal列 = Table.AddColumn(添加匹配列, "Goal", each Text.Combine(List.Transform([匹配的Sections], each _[section]), ", ")),
    清理列 = Table.RemoveColumns(生成Goal列,{"匹配的Sections"})
in
    清理列

2. SQL 实现(以MySQL/SQL Server为例)

MySQL 版本

SELECT 
    m.*,
    GROUP_CONCAT(t.section SEPARATOR ', ') AS Goal
FROM Main m
LEFT JOIN Table1 t 
    ON t.start_depth <= m.Specified_Depth 
    AND t.end_depth >= m.Specified_Depth
GROUP BY m.item_id; -- 替换为Main表的主键或唯一标识列

SQL Server 版本

SELECT 
    m.*,
    STRING_AGG(t.section, ', ') AS Goal
FROM Main m
LEFT JOIN Table1 t 
    ON t.start_depth <= m.Specified_Depth 
    AND t.end_depth >= m.Specified_Depth
GROUP BY m.item_id; -- 替换为Main表的主键或唯一标识列

3. Python Pandas 实现

import pandas as pd

# 读取两张表的数据
main_df = pd.read_excel("你的文件路径.xlsx", sheet_name="Main")
table1_df = pd.read_excel("你的文件路径.xlsx", sheet_name="Table1")

# 交叉合并后筛选符合区间条件的行
merged = pd.merge(main_df, table1_df, how="cross")
filtered = merged[(merged["start深度"] <= merged["Specified Depth"]) & (merged["end深度"] >= merged["Specified Depth"])]

# 聚合生成Goal列,补全未匹配到的空值
goal_df = filtered.groupby(main_df.columns.tolist())["section"].agg(', '.join).reset_index(name="Goal")
final_df = pd.merge(main_df, goal_df, on=main_df.columns.tolist(), how="left").fillna({"Goal": ""})

# 输出结果
print(final_df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 04:27:10