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

SQL查询优化:合并同一visitor_id的多行非null数据为单行

合并visitor_id的账户ID记录,实现一行展示

修正后的SQL查询

SELECT
  p.visitor_id,
  MAX(CASE WHEN p.visitor_id = c.username THEN c.accountId END) AS correct_account_id,
  MAX(CASE WHEN c.accountId IS NULL THEN p.account_id END) AS incorrect_account_id
FROM `a_table` p
LEFT JOIN `another_table` c
  ON p.account_id = c.accountID
GROUP BY p.visitor_id

逻辑说明

原查询通过LEFT JOIN关联两张表后,同一visitor_id会因匹配/不匹配another_table的记录生成多条结果,DISTINCT仅能去重但无法合并同一访客下的非null值。

改用GROUP BY visitor_id将同一访客的所有记录聚合,再通过MAX()函数提取分组内的非null值(聚合函数会自动忽略null),最终实现每个visitor_id对应一行,同时保留正确和错误的账户ID。

期望结果

visitor_idcorrect_account_idincorrect_account_id
1idid

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:34:01