I have a query that returns items like this
Item -- Code -- Thing
------------------------------
Item A -- Code A -- Thing 1
Item A -- Code A -- Thing 2
Item A -- Code A -- Thing 3
Item A -- Code A -- Thing 4
Item B -- Code B -- Thing x
Item B -- Code B -- Thing y
Item C -- Code C -- Thing z
Item C -- Code C -- Thing a
Item C -- Code C -- Thing b
Item C -- Code C -- Thing c
And I want to turn this into something like this
Item -- Code -- Thing 1 -- Thing 2 -- Thing 3 -- Thing 4 -- Thing 5
---------------------------------------------------------------------------
Item A -- Code A -- Thing 1 -- Thing 2 -- Thing 3 -- Thing 4 -- NULL
Item B -- Code B -- Thing x -- Thing y -- NULL -- NULL -- NULL
Item C -- Code C -- Thing a -- Thing b -- Thing c -- Thing d -- NULL
Where any item over 5 can be ignored.
Update:
By adding
“ROW_NUMBER() over (Partition by Table.Id order by Table2.Id)” In my query I now get:
Item -- Code -- Thing -- Index
---------------------------------------
Item A -- Code A -- Thing 1 -- 1
Item A -- Code A -- Thing 2 -- 2
Item A -- Code A -- Thing 3 -- 3
Item A -- Code A -- Thing 4 -- 4
Item B -- Code B -- Thing x -- 1
Item B -- Code B -- Thing y -- 2
Item C -- Code C -- Thing z -- 1
Item C -- Code C -- Thing a -- 2
Item C -- Code C -- Thing b -- 3
Item C -- Code C -- Thing c -- 4
Which allows me to use the Pivot function and change the data accordingly.
Still working on that so any help is very appreciated.
(First try that didn’t work)
One clean way to code this is:
Works because you have a known, limited number of columns to pivot.
The PIVOT function is another way but I am not familiar with this one.
(Second try) This works!
Result:
A A 1 2 3 4 NULL
B B x y NULL NULL NULL
C C f g h j NULL
The trick was to build an ordered list of things first. I used only Code for the lookup as this seems in this case with the data given to be the key (Item didn’t really matter). You might have to extend the join connection.
Using the ordered list I then exclude all Thing(s) that are above the sixth place in order. This only works if Thing(s) is actually a natural order – otherwise it’s back to square one to find out first what Thing(s) is.