KDB+/Q syntax for unique

KDB+ syntax for unique is to use distinct keyword, and it is more powerful.

q)select distinct Sym from t
Sym
—-
AAPL
MSFT
FDS
GS

q)select distinct Sym, Date from t

is same to the following which select the unique combination of Sym,Date

q)distinct select Sym,Date from t
Sym  Date
—————
AAPL 1984.09.07
AAPL 1984.09.10
AAPL 1984.09.11
AAPL 1984.09.12
AAPL 1984.09.13
AAPL 1984.09.14
AAPL 1984.09.17
AAPL 1984.09.18
AAPL 1984.09.19

In KDB+/Q, it is also very useful to use ‘exec’ instead of ‘select’ to return the data in Q list data format instead of table format.

q)exec distinct Sym from t
`AAPL`MSFT`FDS`GS

However, note that the distinct usage for exec is different from select. The distinct can be applied at different field to get the unique data for that particular field.

q)exec distinct Sym, distinct Date from t
Sym | `AAPL`MSFT`FDS`GS
Date| 1984.09.07 1984.09.10 1984.09.11 …

The return result is a dictionary where both Sym and Date field is a list. And the number of element in the list may be different.

q)exec Sym,Date from t
Sym | AAPL       AAPL       AAPL       AAPL       AAPL       AAPL
Date| 1984.09.07 1984.09.10 1984.09.11 1984.09.12 1984.09.13 1984.09.14

Note this would fail:

q)distinct exec Sym,Date from t
‘type

Advertisement

Tags: , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.