我想构建一个OpenSQL查询,以仅返回所有stat
的最大objnr
值。
这有效:
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错误”
答案 0 :(得分:1)
您可以通过按对象编号分组来简化查询,如下所示:
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
答案 1 :(得分:0)
您要查找每stat
个objnr
最高的记录吗?您可以为此使用窗口功能:
select *
from
(
select
jcds.*,
max(stat) over (partition by objnr) as max_stat
from jcds
) data
where stat = max_stat;
答案 2 :(得分:0)
如果我不输错表名,则子选择可以完美地与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 )