|
|
|
Yes this is certainly a common situation where you have to write a query to only extract first or last record from the group.
For example you might want to extract only first product from each category. Let's look at some examples. |
Click here to copy the following block | Drop table #TempTable
Go create table #TempTable ( Bookid int NOT NULL, BLevel varchar (10) NOT NULL, Book varchar (25) NOT NULL, BookRating int NOT NULL )
GO
insert into #TempTable values (1, 'Beginner', 'Learn VB') insert into #TempTable values (2, 'Beginner', 'Learn MS Word') insert into #TempTable values (3, 'Beginner', 'Learn VC++') insert into #TempTable values (4, 'Beginner', 'Learn MS Word') insert into #TempTable values (5, 'Advanced', 'Learn ORACLE') insert into #TempTable values (6, 'Advanced', 'Learn DB2') insert into #TempTable values (7, 'Advanced', 'Learn SQL')
GO
Select * from #TempTable |
Bookid BLevel Book
----------- ---------- -------------------------
1 Beginner Learn VB
2 Beginner Learn MS Word
3 Beginner Learn VC++
4 Beginner Learn MS Word
5 Advanced Learn ORACLE
6 Advanced Learn DB2
7 Advanced Learn SQL
|
Bookid BLevel Book
----------- ---------- -------------------------
5 Advanced Learn ORACLE
1 Beginner Learn VB
|
Bookid BLevel Book
----------- ---------- -------------------------
4 Beginner Learn MS Word
7 Advanced Learn SQL
|
Click here to copy the following block | select t1.* from #TempTable as t1 where t1.Bookid = (select min(t2.BookId) from #TempTable as t2 where t2.BLevel = t1.BLevel) OR t1.Bookid = (select max(t2.BookId) from #TempTable as t2 where t2.BLevel = t1.BLevel) |
Bookid BLevel Book
----------- ---------- -------------------------
1 Beginner Learn VB
4 Beginner Learn MS Word
5 Advanced Learn ORACLE
7 Advanced Learn SQL
|
|
|
|
Submitted By :
Nayan Patel
(Member Since : 5/26/2004 12:23:06 PM)
|
|
|
Job Description :
He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |
View all (893) submissions by this author
(Birth Date : 7/14/1981 ) |
|
|