简体   繁体   中英

How to query for rows that have highest column value among rows that have same value for one of the columns v.2

Still a journeyman to SQL here. I have a temp table named #everything which has the following data. (headers abbreviated). The temp table has many more columns than this.

hh_key sub_id tier
   1    1234   T1
   2    2345   T2
   3    4567   T4
   3    4568   T3

I want to return the rows with the 'best' tier. In my case best has the lowest number after the 'T'. So here are my desired results:

hh_key sub_id tier
   1    1234   T1
   2    2345   T2
   3    4568   T3

I know that this exact issue was asked and resolved here: previous question but the syntax provided in the answer does not work for me. All records are returned, not just the ones with the desired values.

This would be my version of the previous answer and it does not return a subset of values. Everything is returned.

Select household_key, sm_subscription_id ,mytier
from #everything
where Mytier is not null
and Mytier IN (select MIN(mytier) from #everything group by household_key)
order by household_key

Could the fact that I have more than those 3 columns requested from the table be a factor?

You can use ROW_NUMER() :

SUBSTRING(tier, 2, LEN(tier) - 1) will extract the numbers after 'T' . You can use the extracted string and CAST it to INT and use it in the ORDER BY clause of your ROW_NUMBER .

SQL Fiddle

WITH Cte AS(
    SELECT *,
        rn = ROW_NUMBER() OVER(
            PARTITION BY hh_key
            ORDER BY CAST(SUBSTRING(tier, 2, LEN(tier) - 1) AS INT)
        )
    FROM #everything
)
SELECT
    hh_key, sub_id, tier
FROM Cte
WHERE rn = 1
DROP TABLE #everything

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