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
 A Great Query

Author  Topic 

shane1890
Starting Member

3 Posts

Posted - 2010-01-15 : 09:56:24
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:

PROJECT
proj_id orig_proj_id proj_name

1 null Project One
2 null Project Two
3 1 Project One - B1
4 1 Project One - B2
5 2 Project Two - B1
6 1 Project One - B3


I would like a query that returns the most recent baseline of each project, such as follows:

RESULT
proj_id orig_proj_id proj_name

5 2 Project Two - B1
6 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 key

I 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_name
from PROJECT t1 inner join
(
select max(b.proj_id) as proj_id,a.proj_name
from PROJECT a
inner join PROJECT b on b.proj_name like a.proj_name + '%' and a.orig_proj_id is null
group by a.proj_name
) t2
on t1.proj_id = t2.proj_id
order by t1.proj_id
Go to Top of Page

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_name
from
(
row_number() over (partition by isnull(orig_proj_id,proj_id) order by proj_id desc) as seq,
proj_id,
orig_proj_id,
proj_name
from table
)t
where seq=1
Go to Top of Page

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




No ONE Project will have the same name...you need to normalize your data in a BIG way...and the arbitray "PK" has absolutely no meaning



Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam



Go to Top of Page
   

- Advertisement -