Click here to Skip to main content
15,949,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I have a list of account numbers with two/three corresponding codes. However I only need the most recent code and ignore the previous codes, if I were to use a normal join query it will include all the corresponding codes, how do I do the query so it only takes only the most recent code? Thanks for any advice anyone might be able to offer on this.

I tried using a last() but it doesnt work.

SQL
SELECT DISTINCT taa.AS400, taa.Company, taa.Account_Area, taa.Customer_Account, LAST(OMDIM1) as test

FROM dbo.testAccountArea taa

LEFT JOIN dbo.vtbl_orbt_fmosal_vantage sal

ON

taa.AS400 = sal.OMAS400 AND taa.Company = sal.OMCOMP AND taa.Customer_Account = sal.OMCUST
Posted
Updated 24-Jan-11 21:32pm
v2

1 solution

First of all, the statement select distinct ..., last(...) is somewhat strange because there can only be one last record so distinct has no use. I also don't know where OMDIM1 is coming from, but I would try something like this:

select distinct t1.a, t1.b, t1.c from t1 where t1.a = (select last(t2.a) from t2)


It's not the most beautiful sql syntax but for the sake of this example will hopefully do.

Good luck!
 
Share this answer
 
Comments
Yu Ong 25-Jan-11 7:46am    
Hi Thanks for the reply

However, I got an error 'last' is not a recognized built-in function name. Do you know why this could be an issue? Thanks!
E.F. Nijboer 25-Jan-11 8:10am    
Yes, I assumed that you mentioned Last() and that it would be a valid function. It seems it isn't supported in all dialects. Luckily they give an alternative at w3cschool:
http://www.w3schools.com/sql/sql_func_last.asp
Otherwise this could maybe also work: select max(t2.a) from t2 group by t2.a

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900