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
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Last version of each budget!

Author  Topic 

martalex
Starting Member

17 Posts

Posted - 2004-03-11 : 20:18:55
I have the following table.

BudgetItem(BudgetItem_id, budget_id, cash, version)
1, 1, 10, 1
2, 1, 15, 2
3, 2, 25, 1
4, 2, 35, 2
5, 2, 20, 3


How could I retrieve only the last version of each budget?
2, 1, 15, 2
5, 2, 20, 3

jsmith8858
Dr. Cross Join

7423 Posts

Posted - 2004-03-11 : 20:22:35
you have no definition of "last" in your data.

- Jeff
Go to Top of Page

martalex
Starting Member

17 Posts

Posted - 2004-03-11 : 20:47:28
Sorry, last means the the highest version number.
Go to Top of Page

MichaelP
Jedi Yak

2489 Posts

Posted - 2004-03-11 : 21:13:47
Like so:


CREATE TABLE #BudgetItem(BudgetItem_id INT, budget_id INT, cash INT, version INT)

INSERT INTO #BudgetItem(BudgetItem_id, budget_id, cash, version) VALUES(1, 1, 10, 1)

INSERT INTO #BudgetItem(BudgetItem_id, budget_id, cash, version) VALUES(2, 1, 15, 2)

INSERT INTO #BudgetItem(BudgetItem_id, budget_id, cash, version) VALUES(3, 2, 25, 1)

INSERT INTO #BudgetItem(BudgetItem_id, budget_id, cash, version) VALUES(4, 2, 35, 2)

INSERT INTO #BudgetItem(BudgetItem_id, budget_id, cash, version) VALUES(5, 2, 20, 3)

SELECT b.BudgetItem_id, b.budget_id, b.cash, b.version
FROM #BudgetItem b
WHERE b.version = (SELECT MAX(version) FROM #BudgetItem WHERE budget_id = b.budget_id)

DROP TABLE #BudgetItem


In the future, it's really helpful if you can post CREATE TABLE statements like I did above. It makes solving the problem that much quicker.

Enjoy!

Michael

<Yoda>Use the Search page you must. Find the answer you will.</Yoda>
Go to Top of Page
   

- Advertisement -