1

I have two tables, let's call one Items and one Inventory.

The items table has a column for the item#, and then 3 columns for accessories, ACC1, ACC2 and ACC3. The inventory table has item# and quantity on hand.

I would like to be able to display this as:

item#A Acc1 qtyonhand
item#A Acc2 qtyonhand
item#A Acc3 qtyonhand
item#B Acc1 qtyonhand

So that each line would be the item and a unique accessory. If the Acc1,2,or 3 column is empty, the line should not be shown.

How would I write this in SQL? I've failed in every attempt I've made to get these exact results.

Thanks in advance!

2 Answers 2

1

You just have to use UNPIVOT

BEGIN
DECLARE @tbl1 as TABLE(num INT, a1 VARCHAR(16), a2 VARCHAR(16), a3 VARCHAR(16)) 
DECLARE @tbl2 as TABLE(num INT, qty INT)
INSERT INTO @tbl1 VALUES (1, 'a1', 'b1', 'c1'),(2, null, 'b2', null),(3, 'a3', 'b3', 'c3') 
INSERT INTO @tbl2 VALUES (1, 5), (2, 10), (3, 7)

SELECT num, acc [acc], qty FROM (
    SELECT a.num, a.a1, a.a2, a.a3, b.qty FROM @tbl1 a
    LEFT JOIN @tbl2 b ON a.num = b.num
) t1
UNPIVOT (
    value FOR acc IN ([a1], [a2], [a3])
) u
END
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot for the reply. This almost works for me, and I'm sure I just need to do something minor. Based on what you said, I have the code below.
SELECT ItemNumber, acc [acc], QtyOnHandBK FROM ( SELECT a.itemnumber, a.Accessory1, a.Accessory2, a.Accessory3, b.QtyOnHandBK FROM CIX a LEFT JOIN inventory b ON a.itemnumber = b.itemnumber ) t1 UNPIVOT ( value FOR acc IN ([Accessory1], [accessory2], [accessory3]) ) u
(sorry, im new to commenting)...this code above gives me my itemnumber, then "Accessory1", and then the on hand. I want to see the actual accessory item from a.Accessory1. I tried putting a.accessory1 in the [ ] after value FOR acc IN(, but this threw an error. What do I need to change? Thanks a lot for your help.
@user2642976 - You capitalized the A in Accessory1 but not for 2 or 3.
0

The naive way would be to use a UNION:

SELECT i.[item#], ACC1 AS ACC, [quantity on hand]
FROM items i
INNER JOIN inventory inv ON i.[item#] = inv.[item#]
WHERE ACC1 IS NOT NULL
UNION ALL
SELECT i.[item#], ACC2 AS ACC, [quantity on hand]
FROM items i
INNER JOIN inventory inv ON i.[item#] = inv.[item#]
WHERE ACC2 IS NOT NULL
UNION ALL
SELECT i.[item#], ACC3 AS ACC, [quantity on hand]
FROM items i
INNER JOIN inventory inv ON i.[item#] = inv.[item#]
WHERE ACC3 IS NOT NULL

2 Comments

This seems like a brute-force approach when there are directives like UNPIVOT msdn.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx
Thank you, this worked, but I do want to know more about the UNPIVOT optoon

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.