Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

kdb : self join to select duplicate with a condition

I have a table:

t  value 
---------
A    MT 
A    RX
B    SD
B    RX
A    RX 
C    SD

I want to select common values for t=A with other t but without duplicates:

Expected output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

t  value 
---------
A    RX
B    RX

>Solution :

This is a long winded solution so let me break it down

q)distinct select from tab where val in exec val from select from tab where t<>`A,val in exec val from tab where t=`A
t val
-----
A RX
B RX

In the first part we exec values where t=`A

q)exec val from tab where t=`A
`MT`RX`RX

We use this list in the next part of our query which selects from our table where values are in this list, and where t<>`A

q)select from tab where t<>`A,val in exec val from tab where t=`A
t val
-----
B RX

We use the values from our previous query to select from our table

q)select from tab where val in exec val from select from tab where t<>`A,val in exec val from tab where t=`A
t val
-----
A RX
B RX
A RX

Finally, use distinct to remove duplicates

q)distinct select from tab where val in exec val from select from tab where t<>`A,val in exec val from tab where t=`A
t val
-----
A RX
B RX

Note: Since value is a q key word, its advised not to use it as a column name in a table.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading