簡體   English   中英

SQL SERVER QUERY選擇每個項目的最大值記錄

[英]SQL SERVER QUERY to select max value record per item

這是樣本表

在此輸入圖像描述

我需要實現的是僅獲取或顯示月份值最高的租戶記錄。 如果月份相等,我需要根據最新的日期值。 這是所需的輸出樣本

在此輸入圖像描述

有了這個,我開始使用這個代碼使用max函數並合並臨時表,但無法獲得所需的結果。

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


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

並輸出到這樣的東西。 我相信,代碼在整個列表中獲得最大值而不考慮每個租戶過濾。

在此輸入圖像描述

任何幫助將不勝感激 :)

這可以使用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

您可以使用row_number函數。

詢問

;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