开发者

TSQL - Select the rows with the higher count and when count is the same, the row with the higher id value

开发者 https://www.devze.com 2023-04-04 19:35 出处:网络
HELP!!! I\'m stumped and have tried several options to no avail... I need to return one row for each Pub_id, and the row that is returned should be the one with the higher Count and when there is more

HELP!!! I'm stumped and have tried several options to no avail... I need to return one row for each Pub_id, and the row that is returned should be the one with the higher Count and when there is more than one row with the highest count, I need the one with the higher price_id.

I have populated a table with this data...

pub_id, price_id,   count
7,  59431,            5
22, 39964,            4
39, 112831,           3
39, 120715,           2
47, 95359,            2
74, 142825,           5
74, 106688,           5
74, 37514,            1

and This is what I need to return...

pub_id, price_i开发者_如何学Cd,   count
7,  59431,            5
22, 39964,            4
39, 112831,           3
47, 95359,            2
74, 142825,           5


;WITH T
     AS (SELECT *,
                ROW_NUMBER() OVER (PARTITION BY pub_id 
                               ORDER BY [count] DESC, price_id DESC) AS rn
         FROM   your_table)
SELECT pub_id,
       [count],
       price_id
FROM   T  
WHERE rn=1


Do you want something like this

select pub_id,
       Count,
       Price_Id
from   (select Pub_id,
               max(count),
               Price_Id
        from   table_name
        group  by Pub_id) der_tab
group  by Pub_id,
          Count
having Price_id = max(price_Id)  
0

精彩评论

暂无评论...
验证码 换一张
取 消