简体   繁体   English

SQL SERVER QUERY选择每个项目的最大值记录

[英]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. 有了这个,我开始使用这个代码使用max函数并合并临时表,但无法获得所需的结果。

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: 这可以使用row_number窗口函数完成:

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. 您可以使用row_number函数。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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