2014-02-21 60 views
0

我有一個名爲的iView表:選擇與具有共同領域的最高ID的列

gpreq_id a_id m_id  rcv_qty 
1   100  4   0 
2   100  4   1 
3   100  5   4 
4   101  4   1 
5   101  4   10 
6   101  4   1 

如何選擇這個,在A_ID年代M_ID具有最高gpreq_id?

,如:

gpreq_id a_id m_id  rcv_qty 
2   100  4   1 
3   100  5   4 
6   101  4   1 

回答

1

試着這麼做

SELECT i1.* 
FROM iview as i1 
WHERE i1.gpreq_id IN (SELECT MAX(gpreq_id) 
        FROM iview as i2 
        GROUP BY i2.a_id, i2.m_id) 

這裏是SQL FIDDLE

1

首先找到最大值爲每a_id, m_id對,然後加入到IVIEW:

select i.* 
from iview as i 
    inner join (
    select a_id, m_id, max(gpreq_id) as max_gpreq_id 
    from iview 
    group by a_id, m_id 
) as mi on (mi.max_gpreq_id = i.pgreq_ie)