KX Community

Find answers, ask questions, and connect with our KX Community around the world.
KX Community Guidelines

Home Forums kdb+ How do I add column name as a string to content of data Re: How do I add column name as a string to content of data

  • rocuinneagain

    Member
    November 28, 2023 at 12:00 am

    //Sample table

    q)t:([] col1:("abc";"def");col2:("ghi";"jkl")) 
    q)t col1 col2 ----------- "abc" "ghi" "def" "jkl" 
    //qsql update 
    update {"col1#",x} each col1,{"col2#",x} each col2 from t col1 col2 
    --------------------- 
    "col1#abc" "col2#ghi" "col1#def" "col2#jkl" 
    //qsql improved using column name as variable 
    update {string[x],"#",y}[`col1] each col1,{string[x],"#",y}[`col2] each col2 from t col1 col2 
    --------------------- 
    "col1#abc" "col2#ghi" "col1#def" "col2#jkl" \parse the query to see functional form 
    parse"update {string[x],"#",y}[`col1] each col1,{string[x],"#",y}[`col2] each col2 from t" ! `t () 0b `col1`col2!((k){x'y};({string[x],"#",y};,`col1);`col1);(k){x'y};({string[x],"#",y};,`col2);`col2)) 
    //Simplify functional form 
    ![t;();0b;{x!{(each;{string[x],(enlist "#"),y}[x];x)}each x}`col1`col2] col1 col2 
    --------------------- 
    "col1#abc" "col2#ghi" "col1#def" "col2#jkl"