Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
One table. One query. Could you please help?I have a table called PROJECT. Projects can be baselined whereupon a copy is made in the table but this time with the original project name appended with a baseline number. I'll give you an example:
PROJECTproj_id orig_proj_id proj_name1 null Project One2 null Project Two3 1 Project One - B14 1 Project One - B25 2 Project Two - B16 1 Project One - B3
I would like a query that returns the most recent baseline of each project, such as follows:
RESULTproj_id orig_proj_id proj_name5 2 Project Two - B16 1 Project One - B3
Notes:* proj_id is primary key* No two projects will have the same name* The baseline numbering is consistent (B1, B2, B3, ... )* You CANNOT assume anything about the numbering of proj_id, just that it is a primary keyI was thinking of using something like
SELECT TOP 1 * FROM PROJECT WHERE ??? ORDER BY PROJECT.proj_name DESC
but I am not sure.Any help greatly appreciated!
vijayisonly
Master Smack Fu Yak Hacker
1836 Posts
Posted - 2010-01-15 : 10:20:04
Try this..There should be an easier way...but my mind is too slow today...
select t1.proj_id,t1.orig_proj_id,t1.proj_namefrom PROJECT t1 inner join (select max(b.proj_id) as proj_id,a.proj_namefrom PROJECT a inner join PROJECT b on b.proj_name like a.proj_name + '%' and a.orig_proj_id is nullgroup by a.proj_name) t2on t1.proj_id = t2.proj_idorder by t1.proj_id
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2010-01-15 : 12:32:52
if using sql 2005 you can use this also
select proj_id,orig_proj_id,proj_namefrom(row_number() over (partition by isnull(orig_proj_id,proj_id) order by proj_id desc) as seq,proj_id,orig_proj_id,proj_namefrom table)twhere seq=1
X002548
Not Just a Number
15586 Posts
Posted - 2010-01-15 : 12:59:46
quote:Originally posted by shane1890* No two projects will have the same name