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

单表MAX(SEQUENCE)查询正常,关联表后查询异常技术咨询

Fixing Your MAX() Function Issue in Joined Query

Hey there, let's break down why your MAX(B.SEQUENCE) isn't returning the expected maximum value when joining tables—it's all about how the GROUP BY clause is working here.

The Root Problem

In your original joined query, you included B.SEQUENCE in the GROUP BY clause. When you do that, the database splits your results into groups for every unique value of B.SEQUENCE (along with the other grouped fields). That means the MAX(B.SEQUENCE) for each group is just the sequence value of that group itself—not the overall maximum sequence number for your target DOCNUMBER='NUMBER'.

Solutions Based on Your Exact Need

Scenario 1: Get the global max sequence + related details

If you want the single highest SEQUENCE value for DOCNUMBER='NUMBER', plus the corresponding Country, Company, UserID, etc., you need to first find that max sequence, then join back to your tables to pull in the associated data:

SELECT 
    max_seq_tbl.MAX_SEQ,
    A.COUNTRY,
    A.COMPANY,
    A.DOCNUMBER,
    B.USERID,
    B.REASON
FROM TABLE1 A
INNER JOIN TABLE2 B ON A.DOCNUMBER = B.DOCNUMBER
-- First, get the maximum sequence for your target DOCNUMBER
INNER JOIN (
    SELECT DOCNUMBER, MAX(SEQUENCE) AS MAX_SEQ
    FROM TABLE2
    WHERE DOCNUMBER = 'NUMBER'
    GROUP BY DOCNUMBER
) max_seq_tbl ON B.DOCNUMBER = max_seq_tbl.DOCNUMBER 
              AND B.SEQUENCE = max_seq_tbl.MAX_SEQ
WHERE A.DOCNUMBER = 'NUMBER'

Scenario 2: Get max sequence per grouped set of fields

If your goal is to calculate the highest sequence for each unique combination of A.COUNTRY, A.COMPANY, A.DOCNUMBER, B.USERID, B.REASON, you just need to remove B.SEQUENCE from your GROUP BY clause. This way, the database groups by those other fields and computes the max sequence within each group:

SELECT 
    MAX(B.SEQUENCE),
    A.COUNTRY,
    A.COMPANY,
    A.DOCNUMBER,
    B.USERID,
    B.REASON
FROM TABLE1 A
INNER JOIN TABLE2 B ON A.DOCNUMBER = B.DOCNUMBER
WHERE A.DOCNUMBER = 'NUMBER'
GROUP BY A.COUNTRY, A.COMPANY, A.DOCNUMBER, B.USERID, B.REASON

Quick Recap

  • Including B.SEQUENCE in GROUP BY forces the database to create a group for every individual sequence value, making MAX() useless for getting an overall maximum.
  • Choose the solution above that matches what you actually need to retrieve from your query!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:33:49