Instagram
youtube
Facebook
Twitter

Write a Query to Unpivot Inventory Change Logs

Write a Query to Unpivot Inventory Change Logs

InventoryLogs Table:


Query Explanation:

  • UNPIVOT is used to rotate columns into rows — the opposite of PIVOT.

  • In this case, JanQty, FebQty, and MarQty are separate columns.

  • With UNPIVOT, we’re turning them into:

    • One column called Month (which holds: 'JanQty', 'FebQty', 'MarQty')

    • One column called Quantity (which holds the corresponding quantity values)

  • The result will look like:


SQL Query:

SELECT 
    ProductID,
    ProductName,
    Month,
    Quantity
FROM InventoryLogs
UNPIVOT (
    Quantity FOR Month IN (JanQty, FebQty, MarQty)
) AS Unpvt;


Output: