SQL 服务器查询 select 每个项目的最大值记录
SQL SERVER QUERY to select max value record per item
这是样本table
我需要实现的是只获取或显示月值最高的租户记录。如果每个月都相等,我需要基于最新的日期值。这是示例所需的输出
有了这个,我从这个代码开始使用 max 函数并合并了 temp table,但无法得到想要的结果。
select tenant, name, date, month
into #sample
from tenant
select *
from #sample
where months = (select max(months)from #sample)
然后输出成这样。正如我所相信的,代码在不考虑每个租户过滤的情况下获得了整个列表中的最大值。
任何帮助将不胜感激:)
这可以通过 row_number
window 函数来完成:
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;
这是样本table
我需要实现的是只获取或显示月值最高的租户记录。如果每个月都相等,我需要基于最新的日期值。这是示例所需的输出
有了这个,我从这个代码开始使用 max 函数并合并了 temp table,但无法得到想要的结果。
select tenant, name, date, month
into #sample
from tenant
select *
from #sample
where months = (select max(months)from #sample)
然后输出成这样。正如我所相信的,代码在不考虑每个租户过滤的情况下获得了整个列表中的最大值。
任何帮助将不胜感激:)
这可以通过 row_number
window 函数来完成:
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;