选择最大(字段)不起作用

时间:2018-04-06 20:34:27

标签: sql db2 greatest-n-per-group

我有以下问题:

SELECT MAX(SEQUENCE) FROM TABLE1
WHERE FIELD99= 'NUMBER'

该查询带来了Field1的MAX值,并且它的工作正常。 现在我想将这些信息与另一个表格一起收集其他数据,我将使用它:

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 B.SEQUENCE, A.COUNTRY, A.COMPANY, A.DOCNUMBER, B.USERID, B.REASON

我知道问题是分组,但我无法弄清楚,我已经尝试了几种方法,我注意到当我删除所有其他字段时它只带来数据我想。

如果我运行第一个给出的例子,我会得到结果: 007,这是Field SEQUENCE的最大值。 如果我运行另一个Query,我会得到:

001 + all the other fields
002 + all the other fields
003 + all the other fields
004 + all the other fields
005 + all the other fields
006 + all the other fields
007 + all the other fields

我希望结果带来与第一个Query相同的行,并在Select

中添加数据

我能够执行此查询并解决问题

SELECT DISTINCT A.REFFSEQU, A.CTRYCODE, A.COMPCODE, A.INVONUMB, A.REFFERRS, A.REFFERBY              
FROM TABLE1 A, TABLE2 B                                    
WHERE A.CTRYCODE=B.CTRYCODE AND A.COMPCODE=B.COMPCODE AND A.INVONUMB=B.INVONUMB
AND B.INVOCRDT > '20180101'                                                    
AND (A.REFFSEQU = ANY                                                          
 (SELECT MAX(REFFSEQU)                                                         
 FROM TABLE1 AS D                                                    
 WHERE D.CTRYCODE=A.CTRYCODE AND D.COMPCODE=A.COMPCODE                         
 AND D.INVONUMB= A.INVONUMB))                                                  
AND A.REFFERRS = 'DUPLICATION, RECORD REJEC'

这是结果,抱歉不熟悉如何在这里做表

REFFSEQU    CTRYCODE    COMPCODE    INVONUMB    REFFERRS                       REFFERBY
001           631          01   number1         DUPLICATION, RECORD REJEC             id  
002           631          01   number2         DUPLICATION, RECORD REJEC             id
002           631          01   number3         DUPLICATION, RECORD REJEC             id
007           631          01   number4         DUPLICATION, RECORD REJEC             id
007           631          01   number5         DUPLICATION, RECORD REJEC             id

1 个答案:

答案 0 :(得分:0)

我会用CTE来做这件事。它将简化分组。

with tmp as (
  select docnumber, 
         max(sequence) as sequence,
         country,
         company
    from table1
    group by docnumber)
select a.sequence, a.country, a.company, a.docnumber, b.userid, b.reason
  from tmp a
    join table2 b on a.docnumber = b.docnumber
    where a.docnumber = 'NUMBER'

注意,我使用的是table1而不是table2的序列。

编辑:这是基于评论的初步猜测:

with tmp as (
  select docnumber, max(sequence) as sequence
    from table1
    group by docnumber),
tmp2 as (
  select distinct docnumber
    from table2
    where reason = 'Duplicated')
select a.sequence, a.country, a.company, a.docnumber, b.userid, b.reason
  from tmp a
    join table2 b on a.docnumber = b.docnumber
    join tmp2 c on a.docnumber = c.docnumber
    where a.docnumber = 'NUMBER'

如果每个文档编号的序列中只有一个序列的原因为“重复”,则不需要tmp2定义中的distinct。