Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL SERVER QUERY to select max value record per item

This is the sample table

enter image description here

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

enter image description here

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.

enter image description here

Any help will be greatly appreciated :)

like image 521
rickyProgrammer Avatar asked Sep 17 '25 10:09

rickyProgrammer


2 Answers

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
like image 104
sstan Avatar answered Sep 20 '25 03:09

sstan


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;
like image 44
Ullas Avatar answered Sep 20 '25 01:09

Ullas