Thursday 8 August 2013

Selecting MAX on column then MAX from column that is dependent on first value

Selecting MAX on column then MAX from column that is dependent on first value

I have table like this:
CREATE TABLE #Test
(
ParentID int,
DateCreated DATETIME,
ItemNo int
)
INSERT INTO #Test(ParentID, DateCreated, ItemNo) VALUES (1,'2008-10-01
00:00:00.000',0)
INSERT INTO #Test(ParentID, DateCreated, ItemNo) VALUES (1,'2008-10-01
00:00:00.000',1)
INSERT INTO #Test(ParentID, DateCreated, ItemNo) VALUES (1,'2008-05-01
00:00:00.000',2)
INSERT INTO #Test(ParentID, DateCreated, ItemNo) VALUES (1,'2008-05-01
00:00:00.000',3)
INSERT INTO #Test(ParentID, DateCreated, ItemNo) VALUES (2,'2008-06-01
00:00:00.000',3)
INSERT INTO #Test(ParentID, DateCreated, ItemNo) VALUES (2,'2008-06-01
00:00:00.000',4)
INSERT INTO #Test(ParentID, DateCreated, ItemNo) VALUES (2,'2008-04-01
00:00:00.000',6)
INSERT INTO #Test(ParentID, DateCreated, ItemNo) VALUES (2,'2008-04-01
00:00:00.000',8)
I need a way of selecting highest DateCreated with highest ItemNo on same
parentID, and if it is possible to use solution in query like this:
SELECT *
FROM #Test t
JOIN
(
If I could get maximum row here somehow that would be great
) maxt
ON t.ParentID = maxt.ParentID
JOIN SomeOtherTable sot
ON sot.DateCreated = maxt.MaxDateCreated
AND sot.ItemNo = maxt.MaxItemNo
GROUP BY
sot.Something
Just to clarify what results should look like:
ParentID DateCreated ItemNo ParentID
MaxDateCreated MaxItemNo
1, '2008-10-01 00:00:00.000' ,0 1, '2008-10-01
00:00:00.000',1
1, '2008-10-01 00:00:00.000' ,1 1, '2008-10-01
00:00:00.000',1
1, '2008-05-01 00:00:00.000' ,2 1, '2008-10-01
00:00:00.000',1
1, '2008-05-01 00:00:00.000' ,3 1, '2008-10-01
00:00:00.000',1
2, '2008-06-01 00:00:00.000' ,3 2, '2008-06-01
00:00:00.000',4
2, '2008-06-01 00:00:00.000' ,4 2, '2008-06-01
00:00:00.000',4
2, '2008-04-01 00:00:00.000' ,6 2, '2008-06-01
00:00:00.000',4
2, '2008-04-01 00:00:00.000' ,8 2, '2008-06-01
00:00:00.000',4

No comments:

Post a Comment