# Convert Tree into Table columns

**URL:** <https://forum.kx.com/t/convert-tree-into-table-columns/12117>\
**Category:** Community Support\
**Tags:** kdb-and-q\
**Created:** [March 15, 2021, 9:15am UTC](https://forum.kx.com/t/convert-tree-into-table-columns/12117 "2021-03-15T09:15:00Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![KDB\_Dev](https://avatars.discourse-cdn.com/v4/letter/k/3be4f8/32.png) [@KDB\_Dev](https://forum.kx.com/u/KDB_Dev)\
**Post date:** [March 15, 2021, 9:15am UTC](https://forum.kx.com/t/convert-tree-into-table-columns/12117/1 "2021-03-15T09:15:00Z")

</div>

Hi All,

I have a problem statement where I need to convert Tree kind of rows into columns.

&nbsp;  
For Ex:-

I have a table Tree where I have rows as follows :

**Rule&nbsp; &nbsp; &nbsp; &nbsp;| Key&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| Value**  
Rule1&nbsp; &nbsp; &nbsp; | Key1&nbsp; &nbsp; &nbsp; | Val1  
Rule1&nbsp; &nbsp; &nbsp; | Key2&nbsp; &nbsp; &nbsp; | Val2

Rule2&nbsp; &nbsp; &nbsp; | Key1&nbsp; &nbsp; &nbsp; | Val3

Rule2&nbsp; &nbsp; &nbsp; | Key2&nbsp; &nbsp; &nbsp; | Val4

Rule3&nbsp; &nbsp; &nbsp; | Key1&nbsp; &nbsp; &nbsp; | Val5

Rule3&nbsp; &nbsp; &nbsp; | Key2&nbsp; &nbsp; &nbsp; | Val6

Rule3&nbsp; &nbsp; &nbsp; | Key3&nbsp; &nbsp; &nbsp; &nbsp;| Val7

Now I want to convert the unique keys as a column to my output tree and values be the row value.

Output Table :-

**Rule&nbsp; &nbsp; &nbsp; &nbsp;| Key1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| Key2** \*\* &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| Key3\*\*  
Rule1&nbsp; &nbsp; &nbsp;| Val1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | Val2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; |&nbsp;  
Rule2&nbsp; &nbsp; &nbsp;| Val3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | Val4&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; |&nbsp;

Rule3&nbsp; &nbsp; &nbsp;| Val5&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | Val6&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; |&nbsp; Val7

Basically, I want to group all rules together, create columns out of all unique keys and respective values.

Not sure how to do it in kdb. Can somebody help here?

---

<div class="post-metadata">

**Author:** ![ajay1](https://avatars.discourse-cdn.com/v4/letter/a/a3d4f5/32.png) [@ajay1](https://forum.kx.com/u/ajay1)\
**Post date:** [March 15, 2021, 9:33am UTC](https://forum.kx.com/t/convert-tree-into-table-columns/12117/2 "2021-03-15T09:33:00Z")

</div>

https://code.kx.com/q/kb/pivoting-tables/

exec distinct[t`Key]#Key!Val by rule:rule from t

---

<div class="post-metadata">

**Author:** ![KDB\_Dev](https://avatars.discourse-cdn.com/v4/letter/k/3be4f8/32.png) [@KDB\_Dev](https://forum.kx.com/u/KDB_Dev)\
**Post date:** [March 15, 2021, 9:40am UTC](https://forum.kx.com/t/convert-tree-into-table-columns/12117/3 "2021-03-15T09:40:00Z")

</div>

I got the answer post posting this… We can use pivot.. Thanks to KDB…
