Skip to main content

Posts

Showing posts from July, 2009

TOP n of Each -- SQL

Suppose you have a table like this and want to know say the Latest 5 [INPUT] values for all [INST] ie; you have to sort a given INST by date (descending), take the 5 top most from the result. Repeat for each INST and merge all results together. Pretty easy if you have a FOR EACH or some other type of LOOP. [DW_X] ID PROP INST INPUT UPDATEDATE USERID DOMAIN 12 4 1 KUJU 7/14/2009 11:27 1 1 13 4 1 KUJU2 7/14/2009 11:28 1 1 14 4 1 Kuju 7/14/2009 13:41 1 1 15 4 1 kuju2 7/15/2009 9:48 1 1 16 4 1 Kuju3 7/15/2009 13:47 1 1 17 4 6 litlOne 7/15/2009 15:11 1 1 21 4 7 Kuju no 7/16/2009 9:59 1 1 22 4 7 Test1 7/16/2009 13:08 1 1 23 4 7 test2 7/16/2009 13:09 1 1 24 4 1 B 5/16/2009 13:09 NULL 0 25 4 1 C 5/16/2009 13:09 1 0 26 4 1 AA 5/16/2009 13:09 1 0 27 4 1 WW 5/16/2009 13:09 1 0 28 4 1 RR 3/16/2009 13:09 1 0 Instead of loops, you can achieve this by a single SQL statement. Was trying and it works out like this (MS SQL syntax) SELECT * FROM DW_X T1 WHERE T1.ID IN (SELECT TOP 5 T2.ID FROM DW_X T2 WH