问题
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