|
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2001-10-24 : 09:24:08
|
| Robert writes "I do a lot of work with historical tables. My users submit "versions" of the data, each record is time-stamped so I know which is the most recent.When I report that data, I want to perform joins with only the most recent records. To do this I normally create various result tables, and CURSOR through to build up the results I want. But someone out there clever enough must know a better way!!In the example below, the recordset I want is the most recent ETC (estimate to complete) for each project. eg (using short form of date for simplicity)TABLE tAETCproject, estimate, updated-------------------------------------Chocolate, 23, 12-Oct-2001 Chocolate, 12, 19-Oct-2001Strawberry, 10, 12-Oct-2001 Strawberry, 6, 19-Oct-2001TABLE tAPROJECTproject, manager, budget-------------------------------------Chocolate, Fred, 160Strawberry, Ralph, 200Vanilla, Bluey, 300RESULTproject, manager, budget, estimate-------------------------------------Chocolate, Fred, 160, 12 Strawberry, Ralph, 200, 6Vanilla, Bluey, 300, NULLMy question is: Is there any way to achieve this within a SELECT statement?My platform is *NT v4.0 sp 6*SQL Server 2000.......................................................Scripts for building the tables are below.......................................................if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tAPROJECT]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)drop table [dbo].[tAPROJECT]GOCREATE TABLE [dbo].[tAPROJECT] ( [project] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [manager] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [budget] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) ON [PRIMARY]GOif exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tAETC]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)drop table [dbo].[tAETC]GOCREATE TABLE [dbo].[tAETC] ( [project] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [estimate] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [updated] [datetime] NULL ) ON [PRIMARY]GOINSERT INTO [dbo].[tAPROJECT] (project, manager, budget)VALUES ('Chocolate','Fred','160')INSERT INTO [dbo].[tAPROJECT] (project, manager, budget)VALUES ('Strawberry', 'Ralph', '200')INSERT INTO [dbo].[tAPROJECT] (project, manager, budget)VALUES ('Vanilla', 'Bluey', '300')GOINSERT INTO [dbo].[tAETC] (project, estimate, updated)VALUES ('Chocolate', '23', CONVERT(datetime, '12-Oct-2001'))INSERT INTO [dbo].[tAETC] (project, estimate, updated)VALUES ('Chocolate', '12', CONVERT(datetime, '19-Oct-2001'))INSERT INTO [dbo].[tAETC] (project, estimate, updated)VALUES ('Strawberry', '10', CONVERT(datetime, '12-Oct-2001'))INSERT INTO [dbo].[tAETC] (project, estimate, updated)VALUES ('Strawberry', '6', CONVERT(datetime, '19-Oct-2001'))GO/*NOTE - I used nvarchar for the values but this is irrelevant to the problem.*/" |
|