cancel
Showing results for 
Search instead for 
Did you mean: 

help in capstone

VM_67
New Contributor II

4.2.PNG

 

returnN:{[orderColumn;order;N;tab]
// Determine the keywords associated with the ordering required
ascendingOrder: "asc"$order="top";

// Order the table by the column provided in ascending or descending order
ordered: tab order by orderColumn xasc ascendingOrder;

// Subset the first/last N records from the newly ordered table
result: ordered[N sublist orderColumn ] if order="top"
ordered[N # orderColumn] if order="bottom";

// Output table ordering should be in ascending order
result order by orderColumn xasc orderColumn;
}

 

 

I'm stuck here the whole day. if possible, can someone give me the solution to this question.

3 REPLIES 3

RoryK
New Contributor III

It's not very clear what you're trying to do, I'd suggest reading about queries more (https://code.kx.com/q4m3/9_Queries_q-sql/) and maybe looking at other courses (https://kx.com/academy/) for more general help.

 

It is generally better to try for a while and struggle yourself than to get given the answer without properly understanding it. If you have more specific questions, that is fine to ask, but 'can someone give me the solution to this question' is far too broad.

Michaela
Community Manager Community Manager
Community Manager

Hi @VM_67 ,

If you try run your function line by line having defined variables first what happens? Do you get errors on each line?For example taking the first line of your function and defining order to be `top you will get a `type error 

order=`top
ascendingOrder: "asc"$order="top";

Working to resolve these each of these lines in your function will help you work towards a solution. What do you expect to see?

There is also an inbuilt test case returnN.quke that should also help you see if your function is returning expected results.

 

Maybe breaking down the function to do one piece at a time will also help:

1. Order by specified column in the table and parameterise function

`edge xasc tab  // order in ascending order by columm `edge
{[orderColumn] orderColumn xasc tab}`edge // parameterise so can change the orderColumn 

2. Extract top N records

5 sublist `edge xasc tab // get first 5 records 
{[orderColumn;N] N sublist orderColumn xasc tab}[`edge;5] / parameterise so can change the no. records

3. Edit #2 so can get either top or bottom N records depending on the order variable - not going to give the full answer but here's a hint 

Spoiler
N*1 -1 1b
N*1 -1 0b

 

 

 

What is the difference(pros/cons) between sublist and select statements? The course sometimes uses sublists whereas I would use select, even for this example I would write:

N: $[order=`top;N;neg N];
select[N] from t