简体   繁体   English

SQL MAX 查询多列

[英]SQL MAX Query Multiple Columns

Trying to populate multiple columns based on one MAX value but the grouping returns multiple results.尝试根据一个 MAX 值填充多个列,但分组返回多个结果。 Is there a way I can tell SQL to only pull the values based on the MAX that I want?有没有办法告诉 SQL 只根据我想要的 MAX 提取值?

Query:询问:

Select a.ID, (MAX)a.PayDate, a.AgencyName
From a
Group By a.ID, a.AgencyName

What I need is the latest paydate per ID, then I want additional information in reference to that entry such as AgencyName (& more columns I want to add) but because of the grouping - SQL returns the latest paydate for each of the AgencyNames that the person has had - but I only want the AgencyName associated with the record that is Max Paydate for that ID.我需要的是每个 ID 的最新付款日期,然后我需要参考该条目的其他信息,例如 AgencyName(以及我想添加的更多列),但由于分组 - SQL 返回每个 AgencyNames 的最新付款日期人有 - 但我只想要与该 ID 的 Max Paydate 记录相关联的 AgencyName。 I know it's the grouping that does this but I am unsure how to proceed - any help greatly appreciated.我知道这是执行此操作的分组,但我不确定如何进行 - 非常感谢任何帮助。

Thanks谢谢

Select a.ID,a.PayDate, a.AgencyName
From a
where exists (select 1 from a a1 where a1.id = a.id 
  having a.payDate = max(a1.paydate)
Group By a.ID,

I would just use a correlated subquery like this:我只会使用这样的相关子查询:

select a.*
from a
where a.paydate = (select max(a2.paydate) from a a2 where a2.id = a.id);

Note that this could return multiple rows if an id has duplicates on the most recent paydate .请注意,如果id在最近的paydate有重复,这可能会返回多行。 An alternative that guarantees one row is row_number() :保证一行的另一种方法是row_number()

select a.*
from (select a.*,
             row_number() over (partition by id order by paydate desc) as seqnum
      from a
     ) a
where seqnum = 1;

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

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