2023.02.09 06:11 AM - edited 2023.02.09 06:13 AM
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.
2023.02.09 08:50 AM
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.
2023.02.09 09:55 AM
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
N*1 -1 1b
N*1 -1 0b
2023.04.04 04:59 PM
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
EMEA
Tel: +44 (0)28 3025 2242
AMERICAS
Tel: +1 (212) 447 6700
APAC
Tel: +61 (0)2 9236 5700
KX. All Rights Reserved.
KX and kdb+ are registered trademarks of KX Systems, Inc., a subsidiary of FD Technologies plc.