SQL Select MAX and 2nd MAX

我的未来我决定 提交于 2021-01-28 07:01:34

问题


I am running a query against MS SQL Server 2008 and am selecting an accountnumber and the max of the column mydate grouped by accountnumber:

select AccountNumber,
       max(mydate),
from #SampleData
group by AccountNumber

I want to add a column to the result that contains the second highest mydate that is associated with the AccountNumber group. I know it would have to be something like:

select max(mydate)
from #SampleData
where mydate < (select max(mydate) from #SampleData)

But how do I get both the max and 2nd max in one select query?


回答1:


Something like this should select the second highest:

select AccountNumber,
   max(mydate),
   (select max(SD2.mydate) from #SampleData SD2 where SD2.AccountNumber=#SampleData.AccountNumber AND SD2.mydate<max(#SampleData.mydate))
from #SampleData
group by AccountNumber



回答2:


You didn't specify your DBMS so this is ANSI SQL:

select accountnumber,
       rn,
       mydate
from (
   select accountnumber, 
          mydate, 
          row_number() over (partition by accountnumber order by mydate desc) as rn
   from #SampleData
) t
where rn <= 2;



回答3:


Try this

Select AccountNumber,
MAX(Case when Rnum = 1 Then mydate END) mydate_1,
MAX(Case when Rnum = 2 Then mydate END) mydate_2
From
(
select 
AccountNumber, mydate,
ROW_NUMBER() OVER (PARTITION By AccountNumber ORDER BY mydate DESC) as Rnum
from #SampleData
) V
Group By AccountNumber



回答4:


You could also use a TOP N clause combined with an order by:

select    
          TOP 2
          accountnumber, 
          mydate, 
          row_number() over (partition by accountnumber order by mydate desc) as rn
from #SampleData
ORDER BY
          row_number() over (partition by accountnumber order by mydate desc)


来源:https://stackoverflow.com/questions/23942235/sql-select-max-and-2nd-max

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!