sql - Selecting MAX on column then MAX from column that is dependent on first value -
i have table this:
create table #test ( parentid int, datecreated datetime, itemno int ) insert #test(parentid, datecreated, itemno) values (1,'2008-10-01 00:00:00.000',0) insert #test(parentid, datecreated, itemno) values (1,'2008-10-01 00:00:00.000',1) insert #test(parentid, datecreated, itemno) values (1,'2008-05-01 00:00:00.000',2) insert #test(parentid, datecreated, itemno) values (1,'2008-05-01 00:00:00.000',3) insert #test(parentid, datecreated, itemno) values (2,'2008-06-01 00:00:00.000',3) insert #test(parentid, datecreated, itemno) values (2,'2008-06-01 00:00:00.000',4) insert #test(parentid, datecreated, itemno) values (2,'2008-04-01 00:00:00.000',6) insert #test(parentid, datecreated, itemno) values (2,'2008-04-01 00:00:00.000',8)
i need way of selecting highest datecreated highest itemno on same parentid, , if possible use solution in query this:
select * #test t join ( if maximum row here somehow great ) maxt on t.parentid = maxt.parentid join someothertable sot on sot.datecreated = maxt.maxdatecreated , sot.itemno = maxt.maxitemno group sot.something
just clarify results should 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
if need maximum of datecreated , maximum itemno datecreated:
select parentid, datecreated maxdatecreated, itemno maxitemno (select parentid,datecreated,itemno, row_number() on (partition parentid order datecreated desc, itemno desc) rn #test ) t3 rn=1
upd
and results mentioned in question should join #test like:
select * test t join ( select parentid, datecreated maxdatecreated, itemno maxitemno (select parentid,datecreated,itemno, row_number() on (partition parentid order datecreated desc, itemno desc) rn test ) t3 rn=1 ) maxt on t.parentid = maxt.parentid
Comments
Post a Comment