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
3条答案
按热度按时间cedebl8k1#
If you need the Maximum of DateCreated and the Maximum ItemNo for this DateCreated:
SQLFillde demo
UPD
And to get results as mentioned in the question you should join this with #TEST like:
SQLFiddle demo
68bkxrlz2#
93ze6v8z3#
Simpler solution: Using
max(concat(first_column,second_column))
The idea is concat two column then sort it using max.
Example:
select max(concat(first_column,second_column)) from table