简体   繁体   中英

SQL SERVER QUERY to select max value record per item

This is the sample table

在此输入图像描述

What I need to achieve is to get or display only the record of tenant with the highest month value. If ever month is equal, I need to base on the latest date value. Here is the sample desired output

在此输入图像描述

With this, I started by this code using max function and incorporated temp table, but unable to get the desired result.

select tenant, name,  date, month
into #sample
from tenant


select * 
from  #sample  
where months = (select max(months)from #sample)

and output to something like this. As I believe, the code is getting the max value in the whole list not considering per tenant filtering.

在此输入图像描述

Any help will be greatly appreciated :)

This can be done with the row_number window function:

select tenant, name, date, months
  from (select t.*,
               row_number() over (partition by t.tenant, t.name order by t.months desc, t.date desc) as rn
          from TableName t) x
 where rn = 1

You can use a row_number function.

Query

;with cte as 
(
    select rn = row_number() over 
    (
        partition by tenant
        order by months desc,[date] desc
    ),*
    from table_name
)
select tenant,name,[date],months from cte
where rn = 1;

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