简体   繁体   中英

Filter result based on column value

This might seem pretty simple. But after spending sometime, I thought of sharing this. I have the following query.

SELECT *
FROM UPGRADE_HISTORY
ORDER BY MERCHANT_ID, RELEASE_ID

Release_ID lists all the releases corresponds to a particular merchant. In my case, I need to retrieve the result set corresponding to the latest RELEASE_ID per each Merchant.

How can I achieve this?

I think this is what you want:

select uh.*
from upgrade_history uh
where uh.release_id = (select max(uh2.release_id)
                       from upgrade_history uh2
                       where uh2.merchant_id = uh.merchant_id
                      );

This returns one row per merchant, with the largest value of the release id.

The intended query is

SELECT uh.* 
FROM UPGRADE_HISTORY uh
Where uh.RELEASE_ID = (SELECT MAX(RELEASE_ID) 
                       FROM UPGRADE_HISTORY 
                       WHERE MERCHANT_ID=uh.MERCHANT_ID) 
ORDER BY uh.MERCHANT_ID, uh.RELEASE_ID

Try this query (should work):

SELECT 
    *
FROM UPGRADE_HISTORY UH1
INNER JOIN 
(
    SELECT 
        MERCHANT_ID
        ,MAX(RELEASE_ID) RELEASE_ID
    FROM UPGRADE_HISTORY
    GROUP BY MERCHANT_ID
) UH2 ON 
UH2.MERCHANT_ID = UH1.MERCHANT_ID
AND UH2.RELEASE_ID = UH1.RELEASE_ID
select uh.*
from Upgrade_History Uh
where Release_ID>= All( Select Release_ID from Uh2
                        where Uh.Merchant_ID=Uh2.Merchant_ID)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM