Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Last set of rows

Author  Topic 

shanen98
Starting Member

3 Posts

Posted - 2010-08-26 : 11:18:24
I have a database that stores database sizes. At times I simply want to get the last row for each database.

Sample Data

Database(SYSNAME) DataFileSize(INT) Batch(INT PK)
DatabaseA 30 1
DatabaseB 15 2
DatabaseC 40 3
...
DatabaseA 31 7
DatabaseB 15 8
DatabaseC 41 9


To get what I need I am using a temp table. Query:


SELECT DatabaseName, MAX(Batch) AS LastBatch INTO #temp
FROM tblDatabaseSizes
GROUP BY DatabaseName

SELECT * FROM tblDatabaseSizes
WHERE Batch IN (SELECT LastBatch FROM #temp)
ORDER BY DatabaseName

DROP TABLE #temp


Which gives me the data I expect:

DatabaseA 31 7
DatabaseB 15 8
DatabaseC 41 9


It just seems like there should be an easier way to get it. Is there?

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-08-26 : 11:20:23
yup. it is

SELECT DatabaseName,Datafilesize,batch
FROM
(
SELECT DatabaseName,Datafilesize,batch,ROW_NUMBER() OVER (PARTITION BY databasename ORDER BY batch DESC) AS Seq
FROM Table
)t
WHERE Seq=1


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-08-26 : 11:22:11
and if you're using sql 2000 or below, use this

SELECT t.DatabaseName,t.Datafilesize,t.batch
FROM table t
INNER JOIN (SELECT DatabaseName,MAX(batch) AS Latest
FROM table
GROUP BY DatabaseName
)t1
On t1.DatabaseName = t.DatabaseName
AND t1.Latest = t.batch


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

shanen98
Starting Member

3 Posts

Posted - 2010-08-26 : 11:26:20
Thanks Visakh16!

Looks like I need to do some reading on OVER and PARTITION.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-08-26 : 11:28:47
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-08-27 : 08:50:10
To know how effectively make use of row_number() function, refer this
http://beyondrelational.com/blogs/madhivanan/archive/2007/08/27/multipurpose-row-number-function.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -