Skip to main content
Announcements
Live today at 11 AM ET. Get your questions about Qlik Connect answered, or just listen in. SIGN UP NOW
cancel
Showing results for 
Search instead for 
Did you mean: 
shayd
Contributor III
Contributor III

Taking the last n rows from a group by table

WhatsApp Image 2019-12-22 at 09.34.51.jpg

Hi all,

For the table above, created by a group by syntax, I would like to take the last n rows per name.
For example, For Smithy, I would like to create a code that will give me the last n rows, ordered by date of course.
Eventually, this is an example for a million-row table, ID grouped, from which I would like to take per each ID The latest K rows or so.
I need it to be done through the script.

Thanks! 

Labels (1)
1 Solution

Accepted Solutions
Arthur_Fong
Partner - Specialist III
Partner - Specialist III

Try this:

MC.PNG

Script:

let n = 3;   //change this to your last n rows

Raw:
load * inline [
TimeStamp,Name,flag
11/09/2018 15:07:11,Emmy,First
21/09/2018 04:05:50,Emmy,
22/09/2018 17:08:12,Emmy,
07/01/2019 00:00:37,Emmy,
19/02/2019 00:07:58,Emmy,
12/12/2018 21:40:28,Liv,First
];

NoConcatenate
name:
LOAD
    Timestamp#("TimeStamp",'DD/MM/YYYY hh:mm:ss') as "TimeStamp",
    Name,
    flag
resident Raw;
drop table Raw;

tempnames:
LOAD Name,
	 TimeStamp,
     flag,
     Autonumber(TimeStamp, Name) as Rank
RESIDENT name
ORDER BY Name, TimeStamp desc;
DROP TABLE name;

NoConcatenate
names:
load * resident tempnames
where Rank <='$(n)';

drop table tempnames;
//Store names into [lib://names/names.qvd];

Change the inline table to your Excel connection path.

View solution in original post

4 Replies
Arthur_Fong
Partner - Specialist III
Partner - Specialist III

You have a sample app?

shayd
Contributor III
Contributor III
Author

Attached 🙂

Arthur_Fong
Partner - Specialist III
Partner - Specialist III

Try this:

MC.PNG

Script:

let n = 3;   //change this to your last n rows

Raw:
load * inline [
TimeStamp,Name,flag
11/09/2018 15:07:11,Emmy,First
21/09/2018 04:05:50,Emmy,
22/09/2018 17:08:12,Emmy,
07/01/2019 00:00:37,Emmy,
19/02/2019 00:07:58,Emmy,
12/12/2018 21:40:28,Liv,First
];

NoConcatenate
name:
LOAD
    Timestamp#("TimeStamp",'DD/MM/YYYY hh:mm:ss') as "TimeStamp",
    Name,
    flag
resident Raw;
drop table Raw;

tempnames:
LOAD Name,
	 TimeStamp,
     flag,
     Autonumber(TimeStamp, Name) as Rank
RESIDENT name
ORDER BY Name, TimeStamp desc;
DROP TABLE name;

NoConcatenate
names:
load * resident tempnames
where Rank <='$(n)';

drop table tempnames;
//Store names into [lib://names/names.qvd];

Change the inline table to your Excel connection path.

shayd
Contributor III
Contributor III
Author

Worked exactly as I expected.
Thank you Arthur!