Select Max from each Subset

我只是一个虾纸丫 提交于 2019-12-10 14:42:03

问题


I'm banging my head here. I feel pretty stupid because I'm sure I've done something like this before, but can't for the life of me remember how. One of those days I guess >.<

Say I have the following data: ---> and a query which returns this: ---> But I want this:

ID   FirstID              ID   FirstID                ID   FirstID
--   -------              --   -------                --   -------
1     1                   1    1                      7    1
2     1                   3    3                      3    3
3     3                   4    4                      6    4
4     4                   5    5                      5    5
5     5
6     4
7     1

Notice that my query returns the records where ID = FirstID, but I want it to return the Max(ID) for each subset of unique FirstID. Sounds simple enough right? That's what I thought, but I keep getting back just record #7. Here's my query (the one that returns the second block of figures above) with some test code to make your life easier. I need this to give me the results in the far right block. It should be noted that this is a self-joining table where FirstID is a foreign key to ID. Thanks :)

declare @MyTable table (ID int, FirstID int)
insert into @MyTable values (1,1),(2,1),(3,3),(4,4),(5,5),(6,4),(7,1)
select ID, FirstID
from @MyTable
where ID = FirstID

回答1:


Does this work

declare @MyTable table (ID int, FirstID int)
insert into @MyTable values (1,1),(2,1),(3,3),(4,4),(5,5),(6,4),(7,1)

Select FirstID, Max (Id) ID
From @MyTable
Group BY FirstID

Results in

FirstID     ID
----------- -----------
1           7
3           3
4           6
5           5



回答2:


With SQL2005 and later SQL2008 versions the Aggregate functions in SQL Server have been improved

You can use PARTITION BY clause for example with MAX,MIN,SUM,COUNT functions

Please try the following example

select 
Distinct FirstID, Max(ID) OVER (PARTITION BY FirstID) MaxID
from @MyTable 

You can find an example at http://www.kodyaz.com/t-sql/sql-count-function-with-partition-by-clause.aspx

Upon your comment, I modified the same query just to provide the exact output in order of rows and columns as follows

select Distinct 
    Max(ID) OVER (PARTITION BY FirstID) ID,
    FirstID
from @MyTable 
order by FirstID


来源:https://stackoverflow.com/questions/8130591/select-max-from-each-subset

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