# Unpivoting a table

**URL:** https://forum.kx.com/t/unpivoting-a-table/8554
**Category:** Community Support
**Tags:** kdb-and-q
**Created:** [December 23, 2013, 9:47pm UTC](https://forum.kx.com/t/unpivoting-a-table/8554 "2013-12-23T21:47:00Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![leonbaum2](https://avatars.discourse-cdn.com/v4/letter/l/b3f665/32.png) [@leonbaum2](https://forum.kx.com/u/leonbaum2)
#### Post date: [December 23, 2013, 9:47pm UTC](https://forum.kx.com/t/unpivoting-a-table/8554/1 "2013-12-23T21:47:00Z")

</div>

Hi,Following a post on the wiki, I am able to pivot a table on a givencolumn, but I am struggling to reverse the operation.In the example below, I pivot the table “t” on column “x”. I thenattempt to take the resulting table, “t2”, and unpivot it, but I end uplosing column “x”. Is there an elegant solution?q)t: (x: raze 4#’ til 3; y: raze 3# enlist `a`b`c`d; z: 12?1f)q)tx y z --------------0 a 0.5074456 0 b 0.3056222 0 c 0.6886731 0 d 0.2316704 1 a 0.5876646 1 b 0.3976699 1 c 0.3982375 1 d 0.1628311 2 a 0.7589342 2 b 0.8416255 2 c 0.047553262 d 0.217142 q)t2: exec (distinct t`y)#y!z by x:x from tq)t2x| a b c d -| ----------------------------------------0| 0.5074456 0.3056222 0.6886731 0.23167041| 0.5876646 0.3976699 0.3982375 0.16283112| 0.7589342 0.8416255 0.04755326 0.217142 q)raze {( y:key x; z:value x)} each t2y z ------------a 0.5074456 b 0.3056222 c 0.6886731 d 0.2316704 a 0.5876646 b 0.3976699 c 0.3982375 d 0.1628311 a 0.7589342 b 0.8416255 c 0.04755326d 0.217142 Thanks,Leon

---

<div class="post-metadata">

### Author: ![charlie1](https://avatars.discourse-cdn.com/v4/letter/c/ec9cab/32.png) [@charlie1](https://forum.kx.com/u/charlie1)
#### Post date: [December 23, 2013, 10:43pm UTC](https://forum.kx.com/t/unpivoting-a-table/8554/2 "2013-12-23T22:43:00Z")

</div>

changing yours just slightly -

q)t~ungroup{`y`z!(key x;value x)}each t2

1b
