DB2 SQL MAX()SUBQUERY

时间:2014-04-24 14:55:37

标签: sql db2

DATA:
0407340207,0001,0001,0000000,0002  
0407340207,0001,0001,0000000,0007  
0407340207,0001,0001,0000000,0012  
0407340207,0001,0001,0000000,0017  
0407340207,0001,0001,0000000,0022  
0407340207,0001,0001,0000000,0027  
0407340207,0001,0001,0000000,0032  
0407340207,0001,0001,0000000,0037  
0407340207,0001,0001,0000000,0042  
0407340207,0001,0001,0000000,0047  
0407340207,0001,0001,0000000,0052  
0407340207,0001,0001,0000000,0057  
0407340207,0083,0001,0000000,0004  
0407340207,0083,0001,0000000,0009  
0407340207,0083,0001,0000000,0014  
0407340207,0083,0001,0000000,0019  
0407340207,0083,0001,0000000,0024  

我得到了上面的数据,并希望使用max来执行子查询,只获得两行 例如...

0407340207,0001,0001,0000000,0057  
0407340207,0083,0001,0000000,0024  

我做错了什么

SELECT                                                                
    BEI.COLUMN1,                                                    
    BEI.COLUMN2,                                                       
    BEI.COLUMN3,                                                  
    BEI.COLUMN4                                                      
    AND BEI.COLUMN5 = (SELECT MAX(MAXBEI.COLUMN5)                 
    FROM DWHRTB01.BEN_ELEM_INFO BEI                                       
    WHERE BEI.FK_CHNG_DT <= '2014-03-31'                                  
    AND BEI.COLUMN2 IN (01, 80, 81, 83, 84, 105, 106, 107, 108, 137, 138)  
    AND BEI.COLUMN5 = (SELECT MAX(MAXBEI.COLUMN5)                 
    FROM DWHRTB01.BEN_ELEM_INFO MAXBEI                                 
    WHERE (BEI.COLUMN1 = MAXBEI.COLUMN1)                             
    AND (BEI.COLUMN2 = MAXBEI.COLUMN2)                                   
    AND (BEI.COLUMN3 = MAXBEI.COLUMN3)                         
    AND BEI.FK_CHNG_DT <= '2014-03-31'                                 
    AND BEI.COLUMN2 IN (01, 80, 81, 83, 84, 105, 106, 107, 108, 137, 138))

1 个答案:

答案 0 :(得分:0)

一个简单的查询:

SELECT                                                                
    BEI.COLUMN1,                                                    
    BEI.COLUMN2,                                                       
    BEI.COLUMN3,                                                  
    BEI.COLUMN4,
    MAX( BEI.COLUMN5 )
FROM DWHRTB01.BEN_ELEM_INFO BEI
GROUP BY
    BEI.COLUMN1,                                                    
    BEI.COLUMN2,                                                       
    BEI.COLUMN3,                                                  
    BEI.COLUMN4