Welcome Back

Google icon Sign in with Google
OR
I agree to abide by Pharmadaily Terms of Service and its Privacy Policy

Create Account

Google icon Sign up with Google
OR
By signing up, you agree to our Terms of Service and Privacy Policy
Instagram
youtube
Facebook

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, JanQtyFebQty, 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: