The DDL creates the schema and data. I am looking for a where statement where it returns only one row for each ID and that row would be the last inserted row based on the inserteddate column.
So the result would be John, 5 and Debbie, 5
select Table1.Name, Table2.Rating
From table1 join table2 on table1.ID = table2.ID
where inserteddate = max(insertedate)
.. for each ID? It seems simple but I am having a brain block.
DDL:
CREATE TABLE [dbo].[Table1](
[Table1ID] [int] NULL,
[Name] [varchar](50) NULL
)
CREATE TABLE [dbo].[Table2](
[Table2ID] [int] NULL,
[InsertedDate] [datetime] NULL,
[Rating] [varchar](50) NULL
)
INSERT INTO [dbo].[Table1]([Table1ID], [Name])
SELECT 1, N'John' UNION ALL
SELECT 2, N'Debbie'
INSERT INTO [dbo].[Table2]([Table2ID], [InsertedDate], [Rating])
SELECT 1, '20090101 00:00:00.000', N'6' UNION ALL
SELECT 1, '20090401 00:00:00.000', N'5' UNION ALL
SELECT 2, '20090202 00:00:00.000', N'3' UNION ALL
SELECT 2, '20090303 00:00:00.000', N'5'
How about this:
In this case, an index on the
InsertedDatecolumn would be very helpful!Or if you’re on SQL Server 2005 and up, you could also use a CTE (Common Table Expression) with a ROW_NUMBER() and a PARTITION OVER statement like this:
This creates like a “temporary” view (the CTE) and numbers the entries partitioned by Table1ID (individual numbering for each separate Table1ID) and orders them descending by
InsertedDate– so for each unique Table1ID, the most recent entry will have RowNum = 1.Marc