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

如何编写SQL查询按reference_id关联ask_code与对应分组项?

解决分组项与非分组项的关联查询问题

现有一张数据表,包含ask_code、ask_grouping、reference_id三个字段:

  • ask_grouping字段值为G时,对应的ask_code是分组项
  • 非分组项的ask_grouping为空

表中原始数据如下:

ask_codeask_groupingreference_id
A11
TOTALG1
AREAG1
POPULATIONG1
A22
TOTALG2
AREAG2

需要编写SELECT查询,得到以下格式的结果:

ask_codegrouping
A1TOTAL
A1AREA
A1POPULATION
A2TOTAL
A2AREA

解决方案

可以通过自连接实现这个需求,将表中的非分组项与同reference_id下的分组项进行关联:

SELECT 
    non_group.ask_code,
    group_item.ask_code AS grouping
FROM 
    your_table_name non_group
JOIN 
    your_table_name group_item ON non_group.reference_id = group_item.reference_id
WHERE 
    non_group.ask_grouping IS NULL  -- 筛选非分组项
    AND group_item.ask_grouping = 'G'  -- 筛选分组项
ORDER BY 
    non_group.ask_code, group_item.ask_code;

逻辑说明

  1. 给表起两个别名:non_group代表非分组项数据,group_item代表分组项数据
  2. 通过reference_id进行自连接,确保关联的是同一引用ID下的分组与非分组项
  3. WHERE子句分别筛选出非分组项(ask_grouping为空)和分组项(ask_grouping='G')
  4. 最后按ask_code排序,保证结果顺序和目标一致

注意:将SQL中的your_table_name替换成你的实际表名。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:31:14