如何将 SUBSELECT 与 JOIN 一起使用?

How can I use SUBSELECT with JOIN?

我想构建一个 OpenSQL 查询 return 只有所有 objnr 的最大 stat 值。
这有效:

    SELECT O~OBJNR
      FROM JCDS AS O
      WHERE O~OBJNR = 'Obj12345'
      AND STAT = ( SELECT MAX(STAT) 
                     FROM JCDS AS I 
                     WHERE I~OBJNR = O~OBJNR ).

但是,如果我尝试使用联接,而不是直接提供 objnr,我会收到一条错误消息:

    SELECT O~OBJNR, O~STAT
      FROM JCDS AS O
      INNER JOIN AFVC 
          ON AFVB~OBJNR = O~OBJNR
      WHERE "AUFPL" = 'Aufpl12345' 
      AND O~STAT = ( SELECT MAX(STAT) 
                       FROM JCDS AS I 
                       WHERE I~OBJNR = O~OBJNR ).

错误信息无意义; "SQL error"

您可以通过按对象编号分组来简化您的查询:

SELECT O.OBJNR, MAX(O.STAT)
FROM JCDS AS O
GROUP BY O.OBJNR

根据您需要显示连接表中的哪些列,您可以通过以下方式扩展组:

SELECT O.OBJNR, A.SOMECOL, MAX(O.STAT)
FROM JCDS AS O
INNER JOIN AFVC AS A
ON AFVB.OBJNR = O.OBJNR
GROUP BY O.OBJNR, A.SOMECOL

或使用子查询:

SELECT MAXSTAT.OBJNR, MAXSTAT.STAT, A.SOMECOL
FROM (
SELECT O.OBJNR, MAX(O.STAT) STAT
FROM JCDS AS O
GROUP BY O.OBJNR ) MAXSTAT
INNER JOIN AFVC AS A
ON AFVB.OBJNR = MAXSTAT.OBJNR

您是否在寻找每个 objnr 最高 stat 的记录?您可以为此使用 window 函数:

select *
from
(
  select
    jcds.*,
    max(stat) over (partition by objnr) as max_stat
  from jcds
) data
where stat = max_stat;

如果我没有输入错误的表名,子选择可以完美地与 JOIN 一起工作:

    SELECT O~OBJNR, O~STAT
      FROM JCDS AS O
      INNER JOIN AFVC 
    --    ON afvB~OBJNR = O~OBJNR
    --          |
          ON afvC~OBJNR = O~OBJNR
      WHERE "AUFPL" = 'Aufpl12345' 
      AND O~STAT = ( SELECT MAX(STAT) 
                       FROM JCDS AS I 
                       WHERE I~OBJNR = O~OBJNR )