Given a table thus:
ID | Ingredient | Brand | KitchenLocation | PurchaseSize | PurchaseUnit | InStockA | InStockB |
---|---|---|---|---|---|---|---|
14 | Beans, Pinto | Chefs Quality | Pantry | 55 | oz | 15 | 60 |
15 | Beans, Pinto | Chefs Quality | Pantry | 108 | oz | 2 | 7 |
16 | Beans, Pinto | Chefs Quality | Pantry | 648 | oz | 1 | 5 |
17 | Beans, Pinto | First Street | Pantry | 15 | oz | 23 | 10 |
18 | Beans, Pinto | First Street | Pantry | 40 | oz | 5 | 1 |
19 | Beans, Pinto | Sun Vista | Pantry | 29 | oz | 0 | 100 |
I am hoping to find a way of pivoting so the output is grouped by Ingredient, Brand, and KitchenLocation. So the PurchaseSize, PurchaseUnit, InStockA, and InStockB values display as dynamic columns inside this grouping:
Ingredient | Brand | KitchenLocation | Size1 | Unit1 | InStock1A | InStock1B | Size2 | Unit2 | InStock2A | InStock2B | Size3 | Unit3 | InStock3A | InStock3B |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Beans, Pinto | Chefs Quality | Pantry | 55 | oz | 15 | 60 | 108 | oz | 2 | 7 | 648 | oz | 1 | 5 |
Beans, Pinto | First Street | Pantry | 15 | oz | 23 | 10 | 40 | oz | 5 | 1 | ||||
Beans, Pinto | Sun Vista | Pantry | 29 | oz | 0 | 100 |
I can't find an exact question here on Stackoverflow, though of course some are similar. I started to put this code together, but I am stuck, firstly, because Ingredient comes back as NULL in all cases, and secondly I don't know how to dynamically get the new rows to display with a calculated number in the column name (eg. InStock1A, InStock2A etc.):
SELECT Ingredient, Brand, KitchenLocation, InStockA, InStockB
FROM
(SELECT Ingredient AS EIngredient, Brand, KitchenLocation, PurchaseSize, InStockA, InStockB
FROM tmpHoldingTable) AS Source_Table
PIVOT
(MAX(PurchaseSize)
FOR
EIngredient IN (Ingredient)
) AS PIVOT_TABLE
Can anyone point me in the right direction please? Many thanks in advance.