KX Community

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

Home Forums kdb+ select with assignment

  • select with assignment

    Posted by powerpeanuts on September 15, 2022 at 12:00 am

    I remember in q, we can assign a temporary variable during select and use it again in the same column, but seems it is not working.

    For example,

    select (total+5)%(total:a+b) from t

    this should be same as

    select (a+b+5)%(a+b) from t

     

    What is wrong with the above?

    gregbowers replied 9 months, 1 week ago 4 Members · 3 Replies
  • 3 Replies
  • rocuinneagain

    Member
    September 15, 2022 at 12:00 am

    You cannot do inline temporary variable creation as @eohara pointed out.

     

    Instead you can use a lambda to avoid performing the calculation twice:

    q)select {[a;b] (total+5)%(total:a+b)}[a;b] from t 
    b 
    -------- 
    2 
    1.714286 
    1.555556

     

  • eohara

    Member
    September 15, 2022 at 12:00 am

    9. Queries q-sql – Q for Mortals (kx.com)

    “Unlike in SQL, columns in the Select phrase do not actually exist until the final result table is returned. Thus a computed column cannot be used in other column expressions.”

    You’ll need two different select statements here, e.g.

    select (total+5)%total from select total:a+b from t

  • gregbowers

    Member
    March 14, 2024 at 7:42 am

    Hello powerpeanuts,

    In q, the select statement operates in a manner that doesn’t allow for the assignment of temporary variables within the select statement itself. Therefore, the behavior you’re describing, where you can assign a temporary variable during select and reuse it within the same column, isn’t supported.

    The select statement in q typically operates on columns of a table or on the result of an expression, but it doesn’t support intermediate assignment of variables like in some other programming languages.

    To achieve the desired result, you may need to break down the calculation into separate steps or use functions to manipulate the data in the way you intend.

    Thanks for sharing https://learninghub.kx.com/forums/topic/select-with-assignment/salesforce cpq

    Thank you

    Stevediaz

Log in to reply.