pom
pom

Reputation: 340

KDB: how do I print a string literal along each record of table?

How do I select a table along with a string literal value?

tab:flip `items`sales`prices!(`nut`bolt`cam`cog;6 8 0 3;10 20 15 20)

select a:"abcdef", items, sales from tab

Expected output:

    a        items sales prices
    ----------------------------
    "abcdef" nut   6     10
    "abcdef" bolt  8     20
    "abcdef" cam   0     15
    "abcdef" cog   3     20

Upvotes: 1

Views: 759

Answers (3)

terrylynch
terrylynch

Reputation: 13572

You can do it within a select statement provided the fabricated column isn't first

q)select items,a:count[i]#enlist"abcdef",sales from tab
items a        sales
--------------------
nut   "abcdef" 6
bolt  "abcdef" 8
cam   "abcdef" 0
cog   "abcdef" 3

If the fabricated column is first then it groups the values into lists which would require an ungroup

An alternative but less conventional approach would be to use cross

q)([]a:enlist "abcdef")cross tab
a        items sales prices
---------------------------
"abcdef" nut   6     10
"abcdef" bolt  8     20
"abcdef" cam   0     15
"abcdef" cog   3     20

Upvotes: 2

nyi
nyi

Reputation: 3229

In case if you just want to add a new column to a table; here we are using the KDB hidden index column for counting the records.

q)update a:count[i]#enlist "abcdef" from tab
items sales prices a
---------------------------
nut   6     10     "abcdef"
bolt  8     20     "abcdef"
cam   0     15     "abcdef"
cog   3     20     "abcdef"

Upvotes: 3

Rahul
Rahul

Reputation: 3969

you can do this:

 q) update a:count[t]#enlist "abcdef" from t:select items, sales from tab

This will also work if you have where clause:

  q)update a:count[t]#enlist "abcdef" from t:select items, sales from tab where sales<4

Output:

     a      items sales prices
    ----------------------------
    "abcdef" cam   0     15
    "abcdef" cog   3     20

Upvotes: 1

Related Questions